oop's using Java 1.pdf

Full Transcript

A Book Of OBJECT ORIENTED PROGRAMMING USING JA V A - I For T.Y.B.Sc. Computer Science : Semester – V [Course Code CS 355 : Credits - 2] CBCS Pattern As Per New Syllabus, Effective from June 2021 Dr. Ms. Manisha...

A Book Of OBJECT ORIENTED PROGRAMMING USING JA V A - I For T.Y.B.Sc. Computer Science : Semester – V [Course Code CS 355 : Credits - 2] CBCS Pattern As Per New Syllabus, Effective from June 2021 Dr. Ms. Manisha Bharambe M.Sc. (Comp. Sci.), M.Phil. Ph.D. (Comp. Sci.) Vice Principal, Associate Professor, Department of Computer Science MES's Abasaheb Garware College Pune Ms. Manisha Gadekar M.C.A., (Science), UGC-NET Assistant Professor, Annasaheb Magar College Pune Price ` 600.00 N5865 OBJECT ORIENTED PROGRAMMING USING JAVA - I ISBN 978-93-5451-188-2 Second Edition : September 2022 © : Authors The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any computer storage system or device for distribution including photocopy, recording, taping or information retrieval system or reproduced on any disc, tape, perforated media or other information storage device etc., without the written permission of Authors with whom the rights are reserved. Breach of this condition is liable for legal action. Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any mistake, error or discrepancy so noted and shall be brought to our notice shall be taken care of in the next edition. It is notified that neither the publisher nor the authors or seller shall be responsible for any damage or loss of action to any one, of any kind, in any manner, therefrom. The reader must cross check all the facts and contents with original Government notification or publications. Published By : Polyplate Printed By : NIRALI PRAKASHAN YOGIRAJ PRINTERS AND BINDERS Abhyudaya Pragati, 1312, Shivaji Nagar, Survey No. 10/1A, Ghule Industrial Estate Off J.M. Road, Pune – 411005 Nanded Gaon Road Tel - (020) 25512336/37/39 Nanded, Pune - 411041 Email : [email protected] DISTRIBUTION CENTRES PUNE Nirali Prakashan Nirali Prakashan (For orders outside Pune) (For orders within Pune) S. No. 28/27, Dhayari Narhe Road, Near Asian College 119, Budhwar Peth, Jogeshwari Mandir Lane Pune 411041, Maharashtra Pune 411002, Maharashtra Tel : (020) 24690204; Mobile : 9657703143 Tel : (020) 2445 2044; Mobile : 9657703145 Email : [email protected] Email : [email protected] MUMBAI Nirali Prakashan Rasdhara Co-op. Hsg. Society Ltd., 'D' Wing Ground Floor, 385 S.V.P. Road Girgaum, Mumbai 400004, Maharashtra Mobile : 7045821020, Tel : (022) 2385 6339 / 2386 9976 Email : [email protected] DISTRIBUTION BRANCHES DELHI BENGALURU NAGPUR Nirali Prakashan Nirali Prakashan Nirali Prakashan Room No. 2 Ground Floor Maitri Ground Floor, Jaya Apartments, Above Maratha Mandir, Shop No. 3, 4575/15 Omkar Tower, Agarwal Road No. 99, 6th Cross, 6th Main, First Floor, Rani Jhanshi Square, Darya Ganj, New Delhi 110002 Malleswaram, Bengaluru 560003 Sitabuldi Nagpur 440012 (MAH) Mobile : 9555778814/9818561840 Karnataka; Mob : 9686821074 Tel : (0712) 254 7129 Email : [email protected] Email : [email protected] Email : [email protected] KOLHAPUR JALGAON SOLAPUR Nirali Prakashan Nirali Prakashan Nirali Prakashan New Mahadvar Road, Kedar Plaza, 34, V. V. Golani Market, Navi Peth, R-158/2, Avanti Nagar, Near Golden 1st Floor Opp. IDBI Bank Jalgaon 425001, Maharashtra Gate, Pune Naka Chowk Kolhapur 416 012 Maharashtra Tel : (0257) 222 0395 Solapur 413001, Maharashtra Mob : 9850046155 Mob : 94234 91860 Mobile 9890918687 Email : [email protected] Email : [email protected] Email : [email protected] [email protected] | www.pragationline.com Also find us on www.facebook.com/niralibooks Preface … We take an opportunity to present this Text Book on "Object Oriented Programming Using Java - I" to the students of Third Year B.Sc. (Computer Science) Semester-V as per the New Syllabus, June 2021. The book has its own unique features. It brings out the subject in a very simple and lucid manner for easy and comprehensive understanding of the basic concepts. The book covers theory of An Introduction to Java, Objects and Classes, Inheritance and Interface, Exception and File Handling and User Interface with AWT and Swing. A special word of thank to Shri. Dineshbhai Furia, and Mr. Jignesh Furia for showing full faith in us to write this text book. We also thank to Mr. Amar Salunkhe and Mr. Akbar Shaikh of M/s Nirali Prakashan for their excellent co-operation. We also thank Ms. Chaitali Takle, Mr. Ravindra Walodare, Mr. Sachin Shinde, Mr. Ashok Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat. Although every care has been taken to check mistakes and misprints, any errors, omission and suggestions from teachers and students for the improvement of this text book shall be most welcome. Authors Syllabus … 1. An Introduction to Java (6 Lectures) Object Oriented Programming Concepts A Short History of Java Features or Buzzwords of Java Java Environment Simple Java Program Java Tools – jdb, javap, javadoc Types of Comments Data Types Final Variable Declaring 1D, 2D Array Accepting Input (Command Line Arguments, BufferedReader, Scanner) 2. Objects and Classes (7 Lectures) Defining Your Own Classes Access Specifiers - (public, protected, private, default) Array of Objects Constructors, Overloading Constructors and Use of ‘this’ Keyword, Static Block, Static Fields and Methods Predefined Classes o Object Class, Methods (equals(), toString(), hashcode(), getClass()) o String Class and StringBuffer Class, Formatting String Data using format() Method Creating, Accessing and Using Packages Wrapper Classes 3. Inheritance and Interface (8 Lectures) Inheritance Basics (extends Keyword) and Types of Inheritance Superclass, Subclass and Use of Super Keyword Method Overriding and Runtime Polymorphism Use of Final Keyword related to Method and Class Use of Abstract Class and Abstract Methods Defining and Implementing Interfaces Runtime Polymorphism using Interface Concept of Marker and Functional Interfaces 4. Exception and File Handling (5 Lectures) Dealing with Errors, Exception Class, Checked and Unchecked Exception Catching Exceptions, Multiple Catch Block, Nested Try Block Creating User Defined Exception Introduction to Files and Streams Input-OutputStream: FileInput/OutputStream, BufferedInput/OutputStream, DataInput/OutputStream Reader-Writer: FileReader/Writer, BufferedReader/Writer, InputStreamReader, OutputStreamWriter 5. User Interface with AWT and Swing (10 Lectures) What is AWT? What is Swing? Difference between AWT and Swing The MVC Architecture and Swing Layouts and Layout Managers Containers and Components – JFrame, JButton, JLabel, JText, JTextArea, JCheckBox and JRadioButton, JList, JComboBox, JMenu and related Classes Dialogs (Message, Confirmation, Input), JFileChooser, JColorChooser Event Handling: Event Sources, Listeners Adapters and Anonymous Inner Class Contents … 1. An Introduction to Java 1.1 – 1.104 2. Objects and Classes 2.1 – 2.92 3. Inheritance and Interface 3.1 – 3.62 4. Exception and File Handling 4.1 – 4.72 5. User Interface with AWT and Swing 5.1 – 5.126 CHAPTER 1 An Introduction to Java Objectives… To understand Basic Concepts of Java Programming To learn Java Environment To study Java Tools To study Arrays in Java 1.0 INTRODUCTION Java is a general-purpose, high level, robust, Object-Oriented Programming (OOP) language developed by Sun Microsystems in 1991. OOP is a programming paradigm that uses objects and their interactions to design applications and computer programs. A programming paradigm describes the structure of a program. In other words, it determines how the instructions are placed in a program. Java programming language was initiated by James Gosling. He is called father of Java programming. The first version of Java 1.0 was released by Sun Microsystems in 1995. It made the promise of "Write Once, Run Anywhere (WORA)", with free (no cost) runtimes on popular platforms such as Enterprise applications. With the advancement of Java and its widespread popularity, use new enhanced versions of Java have been released. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java Platform, Standard Edition (Java SE) is a computing platform for development and deployment of portable code for desktop and server environments. Java SE was formerly known as Java 2 Platform, Standard Edition (J2SE). Java Platform, Micro Edition (Java ME) is a computing platform for development and deployment of portable code for embedded and mobile devices (micro-controllers, sensors, mobile phones, Personal Digital Assistants (PDAs etc.)). Java ME was formerly known as Java 2 Platform, Micro Edition (J2ME). Java Platform, Enterprise Edition (Java EE) is a computing platform, extending Java SE with specifications for enterprise features such as distributed computing and web services. Java EE was formerly known as Java 2 Platform, Enterprise Edition (J2EE). 1.1 Object Oriented Programming using Java - I An Introduction to Java The latest release/version of the Java programming language is Java SE 16. Java 16 contains new features, enhancements and bug fixes to improve efficiency to develop and run Java programs. Java programming language is mainly used to create these following four types of applications: 1. Web Applications: Web application is an application which creates a dynamic page and runs on the side of server. At present time, technologies that are used to create web application in Java programming language are Struts, Spring, Servlet, Hibernate, JSP, JSF, etc. 2. Mobile Applications: Mobile application refers to application that is developed for mobile devices. At present time, platforms that are used to develop mobile applications in Java programming language are Java ME and Android. 3. Standalone Applications: Desktop applications and Window based applications are the other name of standalone applications. We need to install this traditional software on every machine. Media player and antivirus are the examples of these applications. At current time, for the creation of standalone applications AWT and swing are used in Java programming language. 4. Enterprise Applications: Enterprise applications are those applications which are distributed in nature. Banking application is the example of enterprise applications. It gives programmer the advantage of high level security, clustering and load balancing. At present time, EJB is used in Java programming language for developing enterprise applications. 1.1 OBJECT ORIENTED PROGRAMMING CONCEPTS [April 17] Java is an Object Oriented Programming (OOP) language. The fundamental idea behind an OOP is to combine both data and the functions that operate on the data into a single unit i.e., an object. An approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand is known as Object Oriented Programming (OOP). The popular object-oriented languages include Simula, Ada, Smalltalk, Java, C#, PHP, Python, C++ and so on. Java is a high-level programming language designed and developed to accommodate object-oriented concepts like polymorphism, class, object, abstraction, encapsulation, inheritance, message passing and so on. Features of OOP: 1. OOP emphasis on data rather than procedure. 2. OOP follows bottom-up approach in program design. 3. Programs in OOP are divided into objects. 4. Objects in OOP may communicate with each other through functions. 1.2 Object Oriented Programming using Java - I An Introduction to Java 5. Objects in OOP are characterized by functions or data structure that operates on data. 6. In OOP new data and functions can be easily added whenever necessary. 7. In OOP data is hidden and cannot be accessed by external functions. The fundamental concepts of object oriented programming are explained below: 1. Classes: A class is a blueprint/template from which individual objects are created. A class is a collection of objects of similar type of objects. Classes are user defined data type. Once, class has been defined, we can create any number of object belonging to that class. A class consists of data and methods. A method is a collection of statements that are group together to perform an operation. Following example define class Person with data and methods: class Person { String name; //data int age; void accept( String n, int a) // methods { name=n; age=a; } void display() { System.out.println(“Name=”+name); System.out.println(“Age=”+age); } } 2. Objects: Objects are basic run time entities in OOP. Objects may represent a real-world entity such as a book, a chair, a place, a bank account, a table etc. An object is an instance of a class. Objects are variables of class because it is created by the class data type. An object has two general characteristics namely, state and behavior. An object's state represents what the object knows. The state is maintained in one or more variables associated with the object. An object's behavior represents what the object can do. The behavior is implemented by defined methods that the object can access. Simply put, a method is a named block of code that does something. 1.3 Object Oriented Programming using Java - I An Introduction to Java An object has identity which differentiates one object from the other. Object name is used to identify the object. Hence, name itself is an identity. Objects are generally used to access members (data and methods) of class. For example: Person p = new Person();. In this statement 'p' is an object of Person class. Fig. 1.1 shows example of class and objects. Fig. 1.1 shows class Car has objects like Audi, Nissan, Volvo. class objects Car Audi Nissan Volvo Fig. 1.1: Example of Class and Object Comparison between Object and Class: Sr. No. Object Class 1. Object is an instance of a class. Class is a blueprint or template from which objects are created. 2. Object is a real world entity such as a Class is a group of similar type pen, a laptop, a keyboard, etc. objects. 3. Object is a physical entity. Class is a logical entity. 4. Mainly Object is created through new Class is declared using class keyword keyword like like class Student{ … } Student s1=new Student(); 5. Object is created many times as per Class is declared or created once. requirement. 6. Object allocates memory when it is Class doesn't allocated memory when created. it is created. 3. Data Abstraction: Data abstraction refers to act of representing essential features without including background details or explanations. Classes use the concept of abstraction. They encapsulate all essential properties of objects that they are to be created. Since, the class used the concept of data abstraction they are known as Abstract Data Types (ADT). 4. Data Encapsulation: Data encapsulation means wrapping or binding of data and functions into a single unit. 1.4 Object Oriented Programming using Java - I An Introduction to Java The data is not accessible to the outside world and only functions which are wrapped in the class can access it. Thus, insulation of data from direct access from program is called data hiding. 5. Inheritance: Inheritance is the process by which object of one class can acquire the properties of the objects of another class. Inheritance means one class of object inherits the data and behavior (methods) from another class. The old class is referred as a base class (parent class or super class) and new class is called as derived class (child class or sub class). The new class has combined features of both the classes. Fig. 1.2 shows a class called Vehicle, which has two subclasses called Car and Truck. The Vehicle class is the superclass of Car and Truck. Vehicle Car Truck Fig. 1.2: Classes Car and Truck inherits from the class Vehicle 6. Polymorphism: Polymorphism is the ability to take more than one form. In short, polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. For example: An operation may demonstrate different behavior in different instance. The behavior depends upon the type of data used in the operation. As addition of two integer numbers give addition while addition of two strings give concatenation. 7. Dynamic Binding: Binding refers to the linking of a procedure call to the procedure definition (code) to be executed in response to the call. Binding is classified as static binding and dynamic binding as explained below: (i) Static Binding means that the code associated with given procedure call is known at compile time. (ii) Dynamic Binding means that the code associated with given procedure call is not known until the time of the call at run time. Dynamic binding associated with polymorphism and inheritance. 8. Message Passing: In OOP objects are communicate with each other through message passing. A message for an object is a request for execution of a method. 1.5 Object Oriented Programming using Java - I An Introduction to Java Message passing involves specifying the name of object, the name of the method and the information to be sent. For example: p.accept(“abc”,18); here, p is an object of Person class, accept is message and abc, 18 are arguments is information. Advantages of OOP: 1. Software is easily developed for complex problems. 2. Using OOP, software reuse is enhanced. 3. Using OOP, software maintenance cost can be reduced. 4. Modularity is achieved using OOP. 5. Software has improved performance. 6. Software quality is improved. 7. Data access is restricted providing better data security. Disadvantages of OOP: 1. OOP requires intensive testing procedures. 2. Solving a problem using OOP approach consumes more time than the time taken by structured. 1.2 A SHORT HISTORY OF JAVA In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for consumer electronic devices that could be controlled by a remote. This project was called Stealth Project but later its name was changed to Green Project. Java was developed at Sun Microsystems in 1991, by a team (also called as Green Team) comprising James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan as its members to initiated the project (Green Project) to develop a language for digital devices such as set-top boxes, televisions, etc. in the early 1990s. Java was originally designed for small and embedded systems in digital appliances such as television and set top boxes, etc. But later it suits internet programming and now it is used in mobile applications, enterprise applications, windows applications, etc. James Gosling is known as the father of Java. At first James Gosling called it "Greentalk" but later on the project was developed as green project's part and it was named "Oak". It was later termed as Java. Sun Microsystems released the first public implementation as Java 1.0 in 1996. The Java software was released as a development kit. The first two versions were named JDK 1.0 and JDK 1.1. In 1998, while releasing the next version, Sun Microsystems changed the nomenclature from Java Development Kit (JDK) to Software Development Kit (SDK). Also, it added "2" to the name. The released version of Java was called Java 2 SDK 1.2. 1.6 Object Oriented Programming using Java - I An Introduction to Java With every version, Java became stronger and stronger. At the time of writing of the book, Java had come up with its version SE 8 in April 2014. Table 1.1 illustrates the various versions released of Java language, till date. Table 1.1: History of Java Version Release Date Major Additions JDK 1.0 January 1996 Initial release JDK 1.1 February 1997 Inner classes, JavaBeans JDBC, RMI J2SE 1.2 December 1998 Swing and Collections Framework J2SE 1.3 May 2000 HotSpot JVM, RMI, JavaSound J2SE 1.4 February 2002 Regular expressions, Java Web Start J2SE 5.0 September 2004 Generics, autoboxing, enumeration J2SE SE 6 December 2006 Database manager and many new facilities. JAVA SE 7 July 2011 New invoked dynamic bytecode under JSR-292 JAVA SE 8 March 2014 JDK Enhancement Proposals (JEPS). JAVA SE 9 September, 2017 Fix some open issues and concerns, and to refine some critical technical questions. JAVA SE 10 March, 2018 Security fixes and critical bug fixes. JAVA SE 11 September, 2018 Open for bug fixes. It offers LTS( Long Term Support). JAVA SE 12 March, 2019 Add new features, bug fixes. JAVA SE 13 September, 2019 Text block, bug fixes and security. JAVA SE 14 March, 2020 Pattern matching for instanceof record, Security and Bug fixes. Java SE 15 September, 2020 Security and bug fixes. Java SE 16 March, 2021 Timezone database update, bug fixes, and security updates. 1.3 FEATURES OR BUZZWORDS OF JAVA [April 16, 17, Oct. 17] There are various features of Java as given in Fig. 1.3. Each feature of Java will tell us about how and why Java is a powerful object-oriented programming language. 1.7 Object Oriented Programming using Java - I An Introduction to Java Simple Object- Dynamic oriented Architecure- Secure neutral High- Multi- performance threaded Features Platform Interactive independent Distributed Robust Interpreted Portable Fig. 1.3: Features/Buzzwords of Java Let us see Java features in detail: 1. Simple: Java is a simple language. There are various concepts that make the Java as a simple language. Java is designed to be easy to learn. Programs in Java are easy to write and debug because Java does not use the pointers, preprocessor header files, operator overloading etc. 2. Object-oriented: Java is object-oriented language like C++, Python etc. Almost everything in Java language is an object based. All program code and data in Java reside within objects and classes. Java language can be easily extended since it is based on the Object model. 3. Platform Independent: Java Language is platform independent language. A platform is the hardware or software environment in which a program runs. Java code/program can be run on multiple platforms like Windows, Linux, Sun Solaris, and Mac Os etc. [Oct. 18] 4. Interpreted: Java is an interpreted language, i.e. programs run directly from the source code. Java interpreter can execute Java bytecode directly on any computer machine. This machine should have the interpreter ported on it. Generally, we know that interpreters are very slow. But in Java, the interpreter uses the compiled code called bytecode, so it is faster than typical interpreter. There are compilers available for bytecode called JIT i.e. Just-In Time compilers. These compilers are used to compile the bytecode into native code. So they improve the speed. 1.8 Object Oriented Programming using Java - I An Introduction to Java 5. Distributed: Java facilitates the building of distributed application by a collection of classes for use in networked applications. Java is designed for the distributed environment of the Internet. 6. Dynamic: Java language is capable of dynamically linking in new class libraries, methods and objects. Because Java is interpreted, Java is an extremely dynamic language, at runtime, the Java environment can extends itself by linking in classes that may be located on remote servers on a network, (for example; the Internet). 7. Robust: Java is a robust language because it provides many safeguards to ensure reliable code. Java does not allow pointer which avoids security problem. There is no concept of reference variable. This eliminates the possibility of overwriting memory and corrupting data. Automatic garbage collection eliminates memory leaks. 8. Secure: Java is aimed to be used in networked or distributed environments. Java does not allocate direct pointer to memory, this makes it impossible to accidentally reference memory that belongs to other program. 9. Architecture Neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system. 10. Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Java code is portable. It was an important design goal of Java that it be portable so that as new architectures (due to hardware, operating system, or both) are developed, the Java environment could be ported to them. Additionally, Java is portable because the compiler itself is written in Java. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset. 11. Multithreading: A thread is like a separate program, executing concurrently. Multithreaded means handling multiple tasks simultaneously. With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications. 12. High Performance: With the use of Just-In-Time (JIT) compilers, Java enables high performance. 13. Interactive: Java is called as interactive because code of Java supports CGI (Common Gateway Interface) and GUI (Graphical User Interface) programs. 1.4 JAVA ENVIRONMENT Java environment includes a large number of development tools [part of system known as JDK (Java Development Kit)] and hundreds of classes and methods [(part of the JSL (Java Standard Library)]. 1.9 Object Oriented Programming using Java - I An Introduction to Java The Java Development Kit (JDK) is a software development environment which is used to develop Java applications. JSL also known as the Application Programming Interface (API). The JSL (or API) includes hundreds of classes and methods grouped into several functional packages. Fig. 1.4 depicts a typical Java environment..java file Java compiler.class file Class Loader Byte code Verifier Java Runtime System JVM Native OS Fig. 1.4: Java Environment The Java source code is stored as a ‘.java’ file and is compiled by Java compiler (javac) to get an executable ‘.class’ file. Java compiler translates source code into byte code instructions (.class file). The byte code is executed by JVM (Java Virtual Machine) which is a runtime environment for Java. A ClassLoader is use to download the executable file, the bytecode (instruction set for the Java Virtual Machine (JVM)) of which is then interpreted, a process which makes the file understood by the underlying processor which executes the file instructions. The interpretation process carried by interpreter which reads the instructions and then executes the instructions, step by step. After the bytecode of a class is loaded by the class loader, it has to be inspected by the Java bytecode verifier. Byte code verifier verifies the bytecode so that the code does not make any sort of disturbance for the interpreter. Byte code verifier checks the code fragments for illegal codes that can violate access right to the object. Java uses the Just-In-Time (JIT) compiler with the interpreter, enables all the frequently used class files to be compiled into native code just the once, rather than each time they are used. The API provided by the language is constantly available to the JVM, and the entire package, excepting the compiler that generates the.class file from the.java file, is referred to as the Java Runtime Environment (JRE). JRE is an acronym for Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. 1.10 Object Oriented Programming using Java - I An Introduction to Java Java Virtual Machine (JVM): A JVM is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. A Java virtual machine’s main job is to load class files and execute the byte codes they contain. Fig. 1.5 shows the Java virtual machine contains a class loader, which loads class files from both the program and the Java API. Only those class files from the Java API that are actually needed by a running program are loaded into the virtual machine. The byte codes are executed in an execution engine. The execution engine of JVM is responsible for executing the instructions contained in the methods of loaded classes. When a Java virtual machine runs a program, it needs memory to store many things, including byte codes and other information it extracts from loaded class files, objects the program instantiates, parameters to methods, return values, local variables, and intermediate results of computations. The Java virtual machine organizes the memory it needs to execute a program into several runtime data areas. Class Class files loader subsystem PC Native Method Heap Java registers method area stacks stacks Runtime data areas Native Native method method Execution interface libraries engine Fig. 1.5: Java Virtual Machine (JVM) Java API: The Java API is set of runtime libraries that give us a standard way to access the system resources of a host computer. 1.11 Object Oriented Programming using Java - I An Introduction to Java When we run a Java program, the virtual machine loads the Java API class files that are referred to by the program’s class files. The combination of all loaded class files (from your program and from the Java API) and any loaded dynamic libraries (containing native methods) constitute the full program executed by the Java virtual machine. Java program Java methods (Java API) Native methods (Dynamic libraries) Host operating system Fig. 1.6: Java API The class files of the Java API are inherently specific to the host platform. To access the native resources of the host, the Java API calls native methods. As we can see in Fig. 1.6, the class files of the Java API invoke native methods so your Java program doesn’t have to. In this manner, the Java API’s class files provide a Java program with a standard, platform-independent interface to the underlying host. Precisely because the Java virtual machine and Java API are implemented specifically for each particular host platform, Java programs themselves can be platform independent. The Java Standard Library (JSL or API) includes hundreds of classes and methods grouped into several functional packages. Most commonly used packages are given in following Table 1.2. Table 1.2: Common Packages of JSL Package Name of Description Name Package java.lang Language A collection of classes and methods required for Support Package implementing basic features of Java. java.util Utility Package A collection of classes to provide utility functions such as date and time. contd. … 1.12 Object Oriented Programming using Java - I An Introduction to Java java.io Input/Output A collection of classes for input and output Package manipulation. java.net Networking A collection of classes for communicating with other Package computers. java.awt AWT Package An Abstract Window Toolkit which contains classes and methods for implementing Graphical User Interface. java.applet Applet Package Set of classes to create Java Applets. 1.5 SIMPLE JAVA PROGRAM Program is a set of instructions that tell a computer what to do. A Java program is a collection or set of objects that communicate via invoking each other’s methods. It is necessary to know the exact structure of the Java program. Java program structure means - the way (or general format) to write a Java program. Fig. 1.7 shows basic structure of a Java program. Documentation Section Suggested Package Statement Import Statement Optional Interface Statement Class Definition main method Class { Main method definition Essential } Fig. 1.7: Structure of Java Program Fig. 1.7 shows following sections of a Java Program. 1. Documentation Section: This section is not compiled by java compiler. This section is a set of comment lines giving the name of the program, the author and the other details, which the programmer would like to, refer. 2. Package Statement: Package statement is used by programmer whenever they want to create a package. Package is collection of classes and interface. In Java files, the first statement allowed is a package statement which declares a package name and informs the compiler that the classes defined here belong to this package. Package statement an optional statement. Package statement is written as, package PackageName; For example: package employee; 1.13 Object Oriented Programming using Java - I An Introduction to Java 3. Import Statement: Import statement is used to include java packages or user defined packages in to the program. For example, to include java input output package user can use the statement, import java.io.*;. 4. Interface Statement: An interface is like class used to group of related methods. Interfaces are used when we want to implement or implement multiple inheritance. 5. Class Definition: Classes are an essential part of any Java program. To write a Java program, we first define classes. A Java program may contain many/multiple class definitions. As Java is pure object oriented so each and every code will comes under a class, which consist of main() method. Every program in Java will have at least one class with the main() method. 6. main Method Class: This is essential part of the Java program which is a starting point for JVM to start execution of a Java program. Without the main() method, JVM will not execute the program. In simple words, the execution of a java program starts from main() method. The steps in writing a Java program are illustrated in Fig. 1.8. Step 1 Editor or IDE Write Source Codes Source Codes (.java) Java Compiler Step 2 JDK or 3rd-party APIs Compile (Build) (javac) Java Bytecodes (.class) JDK or 3rd-party APIs and Native Libraries Java Runtime Step 3 (java) Run (Execute) Input Output Fig. 1.8: Steps for create a Java Program Fig. 1.8 shows following steps for creation of a Java program. Step 1 : Write the source codes (.java) using a programming text editor or an IDE (Integrated Development Environment) like Eclipse, NetBeans etc. Step 2 : Compile the source codes (.java) into Java portable bytecodes (.class) using the JDK compiler ("javac"). IDE compiles the source codes automatically while they are entered. Step 3 : Run the compiled bytecodes (.class) with the input to produce the desired output, using the Java Runtime ("java"). 1.14 Object Oriented Programming using Java - I An Introduction to Java To write Java programs, we will need a text editor. A text editor is a type of program used for editing plain text files. The text editors for Java includes Notepad++, jEdit, Editplus and so on. There are even more sophisticated IDEs (Integrated Development Environment) available in the market like Eclipse, Netbeans, JCreator and so on. First Java Program: [Oct. 17, April 18] public class HelloJavaWorld { public static void main(String[] args) { System.out.print("Hello"); System.out.println("Java world!"); } } Output: Hello Java World! Explanation of above Program: o The class keyword is used to declare a class in Java. In the above program, 'HelloWorld' defines the class name in Java. Every class definition in Java begins with an opening brace { and ends with closing brace }. o The public is a keyword and a access specifier indicates that the class member can be accessed from anywhere in the program. o The static keyword indicates that this method can be invoked simply by using the name of the class without creating any class-object. o The void keyword specifies that this method will not return any type of data. The main() method is the main entry point of the program, to start execution. First of all JVM calls the main method of a class and start execution. JVM (Java Virtual Machine) is responsible for running Java programs. o args is a string array that takes values from Java command line. It's index starts from '0'. We can access values by writing args, args etc. o The print word sends the information into a buffer. This buffer is not flushed till a newline or end-of-line character is send. So it prints output on one line and cursor is blinking on the same line. o The println() function prints the output to the standard output stream i.e. monitor. o The out word represents the standard output stream (monitor). Compiling the Program: [Oct. 17] o To compile the HelloWorld program, execute the compiler, javac specifying the name of the source file on the command line. This is shown below: $ javac HelloJavaWorld.java 1.15 Object Oriented Programming using Java - I An Introduction to Java o Javac compiler creates a file named 'HelloJavaWorld.class' which contains the byte code version of the program. It is an intermediate representation of the program. Executing the Program: o To actually run the program we must use the Java application launcher called ‘java’. This is shown below: $ java HelloJavaWorld 1.6 JAVA TOOLS Java platform includes a tool set for development of Java programs. These tools run in a command-line window and provide basic functionality. The Java Development Kit (JDK) comes with a set of tools that are used for developing and running Java program. JDK has a collection of tools for Java program development as shown in Table 1.3. Table 1.3: Java Development Tools Tool Description javac The java compiler that translates javacode to bytecode file which java interpreter can understand. java java is a Java application launcher. It launches a java application by starting Java Runtime Environment, loading a specified class and invoking that class’s main method to run the program. appletviewer Enables us to run java applets. Normally applets are the programs those can be embedded in a web page and run in web browser. This is very useful tool which gives the same effect but on console. javadoc Creates HTML formatted documentation from Java source code files. jdb Java debugger that helps us in finding errors in Java programs. jar Java achieve file, creates a zip/jar file. javah Produces header files for use with native methods. javap Java dissembler which enables us to convert bytecode files into a program description. 1.6.1 javac javac is the primary java compiler included in the JDK. javac is used to compile Java source into bytecode. The java source code is written in files with extension.java. In order to execute the program, these files need to be compiled in.class files. javac translates or converts the ".java" file to a ".class" file. Syntax: $ javac filename.java Example: $ javac HelloJavaWorld.java 1.16 Object Oriented Programming using Java - I An Introduction to Java Fig. 1.9 illustrates the operation of the Java compiler. Compiler Referenced options classes Text Compiler Interpreter Program editor (java c) (java) output/results.java Source files.class files (Bytecode) Fig. 1.9: The operation of the Java compiler (javac) 1.6.2 java In Java language, java is launcher for Java program. java is the interpreter which launches a java program. The java interpreter executes the bytecode files produced by the Java compiler. It translates the Java bytecode into the code that can be understood by the Operating System (OS). Syntax: $ java filename Example: $ java HelloJavaWorld Fig. 1.10 shows java interpreter process. Java program Compiler javac Interpreter Interpreter Interpreter java Win 32 Solaris Mac Fig. 1.10: Java interpreter process 1.6.3 AppletViewer [April 16] An Applet is a Java program that runs in a Web browser. Java AppletViewer is the utility which runs Applets outside the web browser. AppletViewer is a standard JDK tool which has following facilities: 1. To create dynamic applet, and 2. To view java applet. A Java applet is a Java program designed to be included in a HyperText Markup Language (HTML) document and run inside a web browser. 1.17 Object Oriented Programming using Java - I An Introduction to Java Fig. 1.11 shows steps in Applet. Workstation HTML Document 1 2 Internet Java Applet Bytecode Web Server 1. User selects HTML page with embedded applet. 2. Java bytecode is downloaded by browser and executed by integrated bytecode interpreter. Fig. 1.11: Applet 1.6.4 jdb [April 18] The Java debugger (jdb) is a tool for Java classes to debug a program in command line. jdb helps us to find and fix bugs in Java language programs. Debugging is a technical procedure to find and remove bugs or defects in a program and get expected results. A debugger allows us to step through every aspect of a code, inspect all the elements, and remove errors, if any. jdb helps in detecting and fixing bugs in a Java program using Java Debug Interface (JDI). Fig. 1.12 shows the role of jdb in JDK. jdb contains three units i.e., Java Virtual Machine Tool Interface (JVM TI), Java Debug Wiring Pool (JDWP) and Java Debugger Interface (JDI) as shown in Fig. 1.12. Java Development Kit Debuggee JVM (JDK) JVM Tool Interface JDWP Java Debug Wire Protocol JDI Java Debug Interface Debugger JVM (idb) Fig. 1.12: Architecture of jdb 1.18 Object Oriented Programming using Java - I An Introduction to Java 1.6.5 javadoc [April 16, 17, 19] The javadoc tool is a document generator tool in Java for generating standard documentation in HTML format. javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code, which requires documentation in a predefined format. The javadoc is a documentation generator created by Sun Microsystems for the Java language generating API documentation in HTML format from Java source code. The documentation comments (also called doc comments) starts with a slash and two asterisks (). That is why they appear as: Tags are keywords recognized by javadoc which define the type of information that follows. We can use javadoc tags in the doc comments. The syntax of a tag is, @ tag. o All javadoc tags start with @ character. o Each tag must start on a new line. o Various tags are used to provide the heading. o All tags should follow the order. Some common pre-defined tags for javadoc are given below: 1. @author [author name]: Identifies author(s) of a class or interface. 2. @version [version]: Version info of a class or interface. 3. @param [argument name] [argument description]: Describes an argument of method or constructor. 4. @return [description of return]: Describes data returned by method (unnecessary for constructors and void methods). 5. @exception [exception thrown] [exception description]: Describes exception thrown by method. 1.6.6 javap [Oct. 16, 18] The javap tool of Java is used to get the information of any class. In Java the javap command disassembles a class file. The javap command (also known as the Java Disassembler) disassembles one or more class files. The javap tool disassemblies compiled Java files and prints out a representation of the Java program. This may be helpful when the original source code is no longer available on a system. 1.19 Object Oriented Programming using Java - I An Introduction to Java The javap command displays information about the fields, constructors and methods present in a class file. Syntax: javap class_name Example: class Simple { public static void main(String args[]) { System.out.println("hello java"); } } Now let use the javap tool to disassemble the class file. javap Simple Output: Compiled from ".java" class Simple { Simple(); public static void main(java.lang.String[]); } It's output depends on the options used. The important options of javap tools are as follows: Option Description -help Print the help message. -l Prints line number and local variable. -c Disassembles the code. -s Prints internal type signature. -sysinfo Shows system info (path, size, date, MDS hash). -constants Shows static final constants. -version Shows version information. 1.6.7 jar [April 19] jar stands for Java archive. The jar tool is a java application that combines multiple files into a single JAR archive file. jar is a general-purpose archiving and compression tool based on ZIP and the ZLIB compression format. However, jar was designed mainly to facilitate the packaging of java applets or applications into a single archive. Syntax: jar option destinationfile_list 1.20 Object Oriented Programming using Java - I An Introduction to Java Where, destination file_list can have more than one file separated by space, ?, & and * are the wildcard characters used with filenames. Options Description c Creates new or empty ·jar file. f Created jar file named on command line. t Lists the table of contents. v Generates additional output. x Extract the file on command line. 0 (digit zero) No compression and store the file. Example: jar cf first.jar second.class jar tf newjar.jar 1.7 BASIC CONCEPTS IN JAVA In this section we will study basic concepts in Java like variables, data types, constants, comments, identifiers and so on. 1.7.1 Comments Comments are non-executable statements and are ignored by the Java compiler. The comment increases the readability of the programs. Comments help the person/user reading the code better understand the intent and functionality of the program. All characters available inside any comment are ignored by Java compiler. Java language provides three styles or types of comments as given in following table: Sr. Type of Comment Description No. 1. Multi line comments start with. Any text between will be ignored by Java compiler. Example: 2. // Single line comment Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java (will not be executed). Example: // Welcome to Nirali Prakashan. contd. … 1.21 Object Oriented Programming using Java - I An Introduction to Java 3. A doc comment is an ordinary multiline comment that begins with. A doc comment appears immediately before a class, interface, method, or field definition and contains documentation for that class, interface, method, or field. The documentation can include simple HTML formatting tags and other special keywords that provide additional information. Example: Program 1.1: Program for Java comment. public class CommentsDemoExample { public static void main(String args[]) { System.out.println("Hello World"); // This is a Single Live Comment. } } Output: Hello World 1.7.2 Data Types [Oct. 16, April 17] Data types specify the different values that can be stored in the variable. Variables are nothing but reserved memory locations to store values. The type of value that a variable can hold is called as data type. The main purpose of data types in Java is to determine what kind of value we can store into the variable. The data type of a variable determines the value which a variable can contain and the operations that can be performed on it. Every variable must have a data type. Java has a rich set of data types. The data types in Java are shown in Fig. 1.13. 1.22 Object Oriented Programming using Java - I An Introduction to Java Data Types Primitive Non-Primitive Numeric Non-numeric Array Class Integer Non-Integer sring char Boolean int long float double byte short Fig. 1.13: Data Types in Java Java supports two kinds of data types namely, primitive data types or predefined data types and non-primitive data types or reference data types. 1. Primitive Data Types: [Oct. 16] Primitive data types also known as built-in data types, are the fundamental data types provided by a programming language. In Java language primitive data types include integer, floating point, character and Boolean. The eight primitive data types supported by the java programming language are: (i) byte: The byte data type is an 8-bit signed two’s complement integer. It has a maximum value of −128 and a maximum value of 127 (inclusive). (ii) short: The short data type is 16-bit singed two’s complement integer. It has a maximum value of −32,768 and a maximum value of 32,767 (inclusive). (iii) int: The int data type is 32-bit singed two’s complement integer. It has a maximum value of −2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). (iv) long: The long data type is 64-bit singed two’s complement integer. It has a maximum value of −9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,808 (inclusive). Use this data type when you need a range of values wider than those provided by int. (v) float: The float data type is a single-precision 32-byte IEEE 754 Floating point. (vi) double: The float data type is a double-precision 64-byte IEEE 754 Floating point. (vii) boolean: The Boolean data type has only two possible values namely, True and False. Use this data type for simple flags that track true/false conditions. (viii) char: The char data type is single 16-bit Unicode character. It has a maximum value of ‘\u0000’(or 0) and a maximum value of ‘\uffff’(or 65,535 inclusive). 1.23 Object Oriented Programming using Java - I An Introduction to Java Table 1.4 shows data types with their size in bytes. Table 1.4: Data types with their size Sr. No. Data Type Size in Bytes 1. byte 1 2. short 2 3. int 4 4. long 8 5. float 4 6. double 8 7. char 2 2. Non-Primitive Data Types: Non-primitive data types also known as reference data types are derived from the primitive data types. In Java, derived data types include classes, interface, arrays etc. 1.7.3 Tokens The smallest individual units in a Java program are called tokens. Java tokens are smallest elements of a Java program which are identified by the compiler. Tokens in Java include variables, constants, identifiers, keywords, literals, operators, special characters, separators and so on. Java Identifiers: Identifiers are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. In Java, there are several rules for identifiers. They are as follows: 1. All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). 2. After the first character, identifiers can have any combination of characters. 3. A keyword cannot be used as an identifier. 4. Identifiers are case sensitive so Amar and amar has different meaning. Examples of legal identifiers: age, $salary, _phone, _ID. Examples of illegal identifiers: 123abc, -salary. Constants in Java: In java constants, refer to fixed values that do not change during the execution of a program. 1.24 Object Oriented Programming using Java - I An Introduction to Java Constants are also called as literals which has fixed values in a program. Java supports several types of constants below: 1. Integer Constants: An integer constant means the sequence of digits. There are three types of integers: (i) Decimal Integer: Decimal integers consists of a set of digits, 0 through 9 preceded by an optional minus sign. For example: 325, −978, 45673. Embedded spaces, commas and non-digits characters are not allowed between digits. For example: 15 78, $657−, #47 is illegal number. (ii) Octal Integer: An octal integer constant consists of any combination of digits from the set 0 through 7, with al leading 0. For example: 027, 0, 0231, 0341. (iii) Hexadecimal Integer: A sequence of digits preceded by 0X or 0X is considered a hexadecimal integer (hex integer).They may also include alphabet A through F or a through f. A letter A through F represents the number 1 through 15. For example: 0X4, 0X15, 0xabed. 2. Real Constant: Integers numbers are insufficient to represents quantities that vary continuously, such as distance heights, temperature, prices, and so on. Numbers having fractional parts like 17.548 represents these quantities. Such numbers are called real (or floating point) constants. For example: 1.9783, 0 0047 The real number constant can comprise of four parts namely, whole number, decimal point, fractional part and exponent part. These numbers are shown in decimal notation, having a whole number followed by a decimal point and the fractional part, which is an integer. For example: 0.035, 111.98. A real number may also be expressed as in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2 means multiply by 10^2.. For example: 0.65e4, 15e−5, 2.6e+6 56.E4. 3. Character Constant: A single character constant or character constant contains a single character enclosed within a pair of single quote marks. Examples are ‘7’, ‘A’, ‘*’, ‘ ’. The character constant ‘7’ is not the same as the number 7. The last constant is blank space. 4. String Constant: A string constant is a sequence of character enclosed between double quotes in which the character may be alphabets, digits, special characters and blank spaces. For example: “WELCOME”, “@june”, “abhishek”, “!NIDHI!” 1.25 Object Oriented Programming using Java - I An Introduction to Java Backslash Characters: The backslash character constant are used with output statements for getting more effects like tab, new line, single quote etc. Java support some special backslash character constants. A backslah (\) precedes that character to represent it as an escape sequence. For example, the character n represents the alphabet n, where \n represents a new line character. Here, \n is an escape sequence that uses an available printable character n. A list of such backslash character constant is given following table. Each one of them represents one character, although they consist of two character. These characters combinations are known as escape sequences. Backslash Character Constant Meaning \b Back space \f Form feed \n New line \r Carriage return \t Horizontal tab \’ Single quote \” Double quote \\ Backslash Keywords: There are certain words that have a standard, predefined, special meaning in Java. They are called as keywords or reversed words and they can be used only for their intended purposes. These reserved words may not be used as constant or variable or any other identifier names. The keywords in Java are formed using lower case letters only. Keywords in Java are given below: abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while 1.26 Object Oriented Programming using Java - I An Introduction to Java Separator: In java separators are symbols used to show the separated code, they describe function of our code. Table 1.5 shows various type of separators used in Java. Table 1.5: Type of Separators Name Use () Parameter in method definition, containing statements for conditions, etc. {} Used for define a code for method and classes. [] Used for declaration of array. ; Used to show that separate statement. , Used to show the separation in identifier in variable declaration.. Used to show the separate package name from sub-packages and classes, separate variable and method from reference variable. Operators in Java: Operator is a symbol that represents some operation that can be performed on data. Operators perform some specific operations using the operands and operator. For example, answer can be given using expression 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called operator. The operator that uses a single operand is called a unary operator and that which uses two operands is known as a binary operator. A ternary operator uses three operands. Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the various groups Arithmetic Operators, Relational Operators, Bitwise Operators, Logical Operators, and Assignment Operators and so on. 1. Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. Table 1.6 lists the arithmetic operators. Assume integer variable A holds 10 and variable B holds 20. Table 1.6: Arithmetic Operators Sr. Operator Description Example No. 1. + (Addition Adds values on either side of the A + B will give 30 Operator) operator. 2. − (Subtraction Subtracts right hand operand from left A − B will give − 10 Operator) hand operand. contd. … 1.27 Object Oriented Programming using Java - I An Introduction to Java 3. * (Multiplication Multiplies values on either side of the A * B will give 200 Operator) operator. 4. / (Division Divides left hand operand by right B / A will give 2 Operator) hand operand. 5. % (Modulus Divides left hand operand by right B % A will give 0 Operator) hand operand and returns remainder. 6. ++ (Increment Increases the value of operand by 1. B++ gives 21 Operator) 7. −− (Decrement Decreases the value of operand by 1. B−− gives 19 Operator) Program 1.2: Program for arithmetic operators. public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 25; int d = 25; System.out.println("a + b = " + (a + b) ); System.out.println("a - b = " + (a - b) ); System.out.println("a * b = " + (a * b) ); System.out.println("b / a = " + (b / a) ); System.out.println("b % a = " + (b % a) ); System.out.println("c % a = " + (c % a) ); System.out.println("a++ = " + (a++) ); System.out.println("b-- = " + (a--) ); // Check the difference in d++ and ++d System.out.println("d++ = " + (d++) ); System.out.println("++d = " + (++d) ); } } Output: a + b = 30 a - b = -10 a * b = 200 b / a = 2 b % a = 0 c % a = 5 a++ = 10 b-- = 11 d++ = 25 ++d = 27 1.28 Object Oriented Programming using Java - I An Introduction to Java 2. Relational Operators: Relational operators are also called as comparison operators used for comparing values of two variables. Table 1.7 shows relational operators supported by Java language. Assume variable A holds 10 and variable B holds 20. Table 1.7: Relational Operators Sr. Operator Description Example No. 1. == Checks if the values of two operands are equal or (A = = B) is not (Equal to not, if yes then condition becomes true. true. Operator) 2. != (Not Checks if the values of two operands are equal or (A != B) is true. Equal to not, if values are not equal then condition becomes Operator) true. 3. > Checks if the value of left operand is greater than (A > B) is not (Greater the value of right operand, if yes then condition true. than becomes true. Operator) 4. < (Less Checks if the value of left operand is less than the (A < B) is true. than value of right operand, if yes then condition Operator) becomes true. 5. >= ( Checks if the value of left operand is greater than (A >= B) is not Greater or equal to the value of right operand, if yes then true. than or condition becomes true. Equal to Operator) 6. b) ); 1.29 Object Oriented Programming using Java - I An Introduction to Java System.out.println("c = d = " + (c >= d) ); System.out.println("c == d = " + (c == d) ); } } Output: a < b = true c > b = true c = d = true c == d = true 3. Logical Operators: When we want to form compound conditions by combining two or more relations, then we can use logical operators. Logical operators are used to check whether an expression is True or False. Table 1.8 lists the logical operators. Assume Boolean variables A holds True and variable B holds False. Table 1.8: Logical Operators Sr. Operator Description Example No. 1. && (Logical AND Operator) If both the operands are non- (A && B) is zero, then the condition False. becomes true. 2. || (Logical OR Operator) If any of the two operands are (A || B) is True. non-zero, then the condition becomes true. 3. ! (Logical NOT Operator) Use to reverses the logical ! (A && B) is state of its operand. If a True. condition is true then Logical NOT operator will make false. Program 1.4: Program for logical operators. public class Sample { public static void main(String args[]) { int a = 60; int b = 20; int c = 25; int d = 25; System.out.println("(a > b && c == d) = " + (a > b && c == d) ); System.out.println("(a < b && c == d) = " + (a < b && c == d)); System.out.println("(a < b || c == d) " + (a < b || c == d) ); System.out.println(" !(a < b) = " + !(a < b ) ); } } 1.30 Object Oriented Programming using Java - I An Introduction to Java Output: (a > b && c == d) = true (a < b && c == d) = false (a < b || c == d) true !(a < b) = true 4. Assignments Operators: Assignment operators are used to assign values to variables. Table 1.9: Assignments Operators Sr. Operator Description Example No. 1. = (Simple Assignment Assigns values from right C = A + B will assign value of Operator) side operands to left side A + B into C operand 2. += (Add and It adds right operand to C += A is equivalent to C = C Assignment Operator) the left operand and +A assign the result to left operand 3. −= (Subtract and It subtracts right operand C -= A is equivalent to C = C − Assignment Operator) from the left operand and A assign the result to left operand 4. *= (Multiply and It multiplies right C *= A is equivalent to C = C Assignment Operator) operand with the left *A operand and assign the result to left operand 5. /= (Divide and It divides left operand C /= A is equivalent to C = C / Assignment Operator) with the right operand A and assign the result to left operand 6. % = (Modulus and It takes modulus using C %= A is equivalent to C = C Assignment Operator) two operands and assign %A the result to left operand 7. > 2 Assignment Operator. 9. &= Bitwise AND Assignment C &= 2 is same as C = C & 2 Operator. 10. ^= Bitwise Exclusive OR AND C ^= 2 is same as C = C ^ 2 Assignment Operator. 11. |= Bitwise Inclusive OR AND C |= 2 is same as C = C | 2 Assignment Operator. 1.31 Object Oriented Programming using Java - I An Introduction to Java 5. Increment and Decrement operator: Java provides two increment and decrement operators which are unary increment (++) and decrement (−−) operators. Increment and decrement operators are used to increase or decrease the value of an operand by one, the operand must be a variable, an element of an array, or a field of an object. Suppose, a = 5 then, ++a; //a becomes 6 a++; //a becomes 7 --a; //a becomes 6 a--; //a becomes 5 Program 1.5: Program for increment and decrement operators. class Operator { public static void main(String[] args) { int var=5; System.out.println("var++:"+ var++); System.out.println("\n++var:"+ ++var); } } Output: var++:5 ++var:7 6. Conditional Operator (?: ): Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the ternary operator is to decide which value should be assigned to the variable. The syntax for ternary operator is, variable x = (expression) ? value if true: value if false Program 1.6: Program for ternary operator. public class Test { public static void main(String args[]) { int a , b; a=10; b=(a ==1)?20:30; 1.32 Object Oriented Programming using Java - I An Introduction to Java System.out.println("Value of b is: "+ b ); b=(a ==10)?20:30; System.out.println("Value of b is: "+ b ); } } Output: Value of b is:30 Value of b is:20 7. Bitwise Operators: Bitwise operators in Java are used to perform operations on individual bits. Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 Table 1.10 lists the bitwise operators: Assume integer variable A holds 60 and variable B holds 13. Table 1.10: Bitwise Operators Sr. Operator Description Example No. 1. & (Binary AND Operator) Copies a bit to the result (A & B) will give 12 if it exists in both which is 0000 1100 operands. 2. | (Binary OR Operator) Copies a bit if it exists in (A | B) will give 61 either operand. which is 0011 1101 3. ^ (Binary XOR Operator) Copies the bit if it is set (A ^ B) will give 49 in one operand but not which is 0011 0001 both. 4. ~ (Binary Ones (1's) Unary and has the effect (~A) will give -61 which Complement Operator) of 'flipping' bits. is 1100 0011 in 2's complement form due to a signed binary number. contd. … 1.33 Object Oriented Programming using Java - I An Introduction to Java 5. (Binary Right Shift The left operands value A >> 2 will give 15 which Operator) is moved right by the is 1111 number of bits specified by the right operand. 7. >>> (Shift right zero fill The left operands value A >>>2 will give 15 operator) is moved right by the which is 0000 1111 number of bits specified by the right operand and shifted values are filled up with zeros. Program 1.7: Program for bitwise operators. public class Sample { public static void main(String args[]) { int a = 60; int b = 20; System.out.println("a & b = " + (a & b) ); System.out.println("a | b = " + (a | b) ); System.out.println("a > 2 = " + (a >> 2) ); System.out.println("a >>> 2 = " + (a >>> 2) ); } } Output: a & b = 20 a | b = 60 a > 2 = 15 a >>> 2 = 15 8. Special Operators: There are few other operators supported by Java language as explained below: (i) instanceof Operator: This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). 1.34 Object Oriented Programming using Java - I An Introduction to Java The instanceof operator is written as, (Object reference variable) instanceof (class/interface type) If the object on the left side of the operator is an object of right side, then the result will be true. Program 1.8: Program for instanceof operator. public class Test { public static void main(String args[]) { String name ="James"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); } } Output: true (ii) Dot Operator: The dot operator (.) is used to access class members i.e. methods and data. Program 1.9: Program for dot operator. class Person { String name; int age; void display() { System.out.println(“Name=”+name); System.out.println(“Age=”+age); } public static void main(String args[]) { Person p=new Person() p.name=“abc”; p.age=“10”; p.display(); } } Output: Name=abc Age=10 1.35 Object Oriented Programming using Java - I An Introduction to Java Operator Precedence in Java: Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses. Precedence Order: When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition. Operator Associativity in Java: When two operators with the same precedence the expression is evaluated according to its associativity. For example, x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity. Table 1.11 shows the associativity and precedence order of java operators. Table 1.11: Operator Precedence Operators Associativity Precedence Rank (), [] Left to right 1 −, ++, --, ! Right to left 2 *, /, % Left to right 3 +, − Left to right 4 > Left to right 5 = Left to right 6 ==, != Left to right 7 & Left to right 8 ^ Left to right 9 | Left to right 10 && Left to right 11 || Left to right 12 ?: Right to left 13 1.36 Object Oriented Programming using Java - I An Introduction to Java 1.7.4 Variables Variables are containers for storing data values. Variables are the basic units used to store any information in Java. A variable is an identifier that denotes a storage location used to store a data value. The value in the variable can be changed during the program’s execution. Variables are nothing but reserved memory locations to store values. This means that when we create a variable we reserve some space in memory. Following are the some rules used for variable naming: 1. Variable name must begin with either a letter or the dollar sign "$" or the underscore character "_". 2. Variable names are case-sensitive. Upper case and lower case must be distinct this means that the variable Abc is not the same as abc or ABC. 3. Variable must not begin with a digit. 4. White space is not allowed in variable naming. 5. Variable name should not be a keyword. 6. Variable names can be of any length. Variable Declaration: In Java, all the variables must be declared before use. A variable declaration, in its simplest form, includes the name and the data type of variables. Declaration does following three things: 1. It tells variable name to the compiler. 2. It specifies the data type of the data hold by variable. 3. The place of declaration in the program decided the scope of the variable. Following is the basic form/syntax of a variable declaration: data_type variable_Name; Here, data_type is one of Java's data types and variable_Name is the name of the variable. To declare more than one variable of the specified type, you can use a comma- separated list as given below: data_type variable_Name1, variable_Name2, …… variable_NameN; Example: int age; // Declares age int a, b, c; // Declares three ints, a, b, and c. Variable Initialization: Variable initialization means assigning a value to variables. Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). In Java, we can assign a value to variables in two ways: 1. Static: This means that the memory is determined for variables when the program starts. Variables can be assigned initial values at the time of declaration. Assignment operator (=) assigns the value of an expression to a variable. Syntax: variable_name=value; OR data_type variable_name=value; 1.37 Object Oriented Programming using Java - I An Introduction to Java Examples: IntitalValue = 0; a = b = c = 0; int a = 10, b = 10; // Variable initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. 2. Dynamic: Dynamic means that in Java, we can declare variables anywhere in the program, because when the statement is executed the memory is assigned to them. Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is called dynamic initialization. Program 1.10: Program for dynamic initialization of variables. class DynamicInit { public static void main(String args[]) { double a = 3.0, b = 4.0; // c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("C=" + c); } } Output: C=5.0 Scope of Variables: The area of the program where the variable is accessible is called its scope. Scope refers to the lifetime and accessibility of a variable. The scope of a variable defines the section of the code in which the variable is accessible or visible. Scope is the lifetime of a variable and refers to how long the variable exists before it is destroyed. Scope itself specifies that the system allocates and de-allocates the memory for the variable. Java variables are actually clas

Use Quizgecko on...
Browser
Browser