OOPs through Java UNIT 1.pdf
Document Details
Uploaded by Deleted User
2024
Tags
Full Transcript
UNIT-I II B.Tech. I SEM (R22) OOPs through JAVA 2024-25 II-I Department of AI & ML SREYAS Institute of Engineering & Technology Tattiannaram, Hyderabad...
UNIT-I II B.Tech. I SEM (R22) OOPs through JAVA 2024-25 II-I Department of AI & ML SREYAS Institute of Engineering & Technology Tattiannaram, Hyderabad. UNIT 1 By, Dr. Swathi Gowroju UNIT-I II B.Tech. I SEM (R22) UNIT I: Object oriented thinking 1) Need for OOP paradigm The object oriented paradigm is a methodology for producing reusable software components. The object-oriented paradigm is a programming methodology that promotes the efficient designand development of software systems using reusable components that can be quickly and safely assembled into larger systems. Object oriented programming has taken a completely different direction and will place an emphasis on object s and information. With object oriented programming, a problem will be broken down into a number of units.these are called objects.The foundation of OOP is the fact that it will place an emphasis on objects and classes. There are number of advantages to be foundwith using the OOP paradigm, and some of these are OOP paradigm. Object oriented programming is a concept that was created because of the need to overcome the problems that were found with using structured programming techniques. While structured programming uses an approach which is top down, OOP uses an approach which is bottom up. A paradigm is a way in which a computer language looks at the problem to be solved. We divide computer languages into four paradigms: procedural, object-oriented, functional and declarative A paradigm shift from a function-centric approach to an object-centric approach to software development. A program in a procedural paradigm is an active agent that uses passive objects that we refer to as data or data items. The basic unit of code is the class which is a template for creating run-time objects. Classes can be composed from other classes. For example, Clocks can be constructed as an aggregate of Counters. The object-oriented paradigm deals with active objects instead of passive objects. We encounter many active objects in our daily life: a vehicle, an automatic door, a dishwasher and so on. The actions to be performed on these objects are included in the object: the objects need only to receive the appropriate stimulus from outside to perform one of the actions. A file in an object-oriented paradigm can be packed with all the procedures called methods in the object-oriented paradigm—to be performed by the file: printing, copying, deleting and so on. The program in this paradigm just sends the corresponding request to the object. Java provides automatic garbage collection, relieving the programmer of the need to ensure thatunreferenced memory is regularly deallocated. UNIT-I II B.Tech. I SEM (R22) Object Oriented Paradigm – Key Features Encapsulation Abstraction Inheritance Polymorphism 2) A Way of viewing World- Agents A Java agent is a regular Java class which follows a set of strict conventions. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. There are agent development toolkits and agent programming languages. The Agent Identity class defines agent identity. An instance of this class uniquely identifies an agent. Agents use this information to identify the agents with whom they are interested in collaborating. The Agent Host class defines the agent host. An instance of this class keeps track of every agent executing in the system. It works with other hosts in order to transfer agents. The Agent class defines the agent. An instance of this class exists for each agent executing on agiven agent host. OOP uses an approach of treating a real world agent as an object. Object-oriented programming organizes a program around its data (that is, objects) and a set ofwell-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code by switching the controlling entity to data. Responsibility In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of asource of command objects and a series of processing objects. Each processing object contains logicthat defines the types of command objects that it canhandle;the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. Primary motivation is the need for a platform-independent (that is, architecture- neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. UNIT-I II B.Tech. I SEM (R22) Objects with clear responsibilities. Each class should have a clear responsibility. If you can't state the purpose of a class in a single, clear sentence, then perhaps your classstructure needs some thought. In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by theclass. All its services should be narrowly aligned with that responsibility. Messages Message implements the Part interface. Message contains a set of attributes and a "content". Message objects are obtained either from a Folder or by constructing a new Message object of the appropriate subclass. Messages that have been received are normally retrieved from a folder named "INBOX". A Message object obtained from a folder is just a lightweight reference to the actual message.The Message is 'lazily' filled up (on demand) when each item is requested from the message. Note that certain folder implementations may return Message objects that are pre-filled with certain user-specified items. To send a message, an appropriate subclass of Message (e.g., Mime Message) is instantiated, the attributes and content are filled in, and the message is sent using the Transport. Send method. We all like to use programs that let us know what's going on. Programs that keep us informedoften do so by displaying status and error messages. These messages need to be translated so they can be understood by end users around the world. The Section discusses translatable text messages. Usually, you're done after you move amessage String into a Resource Bundle. If you've embedded variable data in a message, you'll have to take some extra steps to prepareit for translation. Methods The only required elements of a method declaration are the method's return type, name, apair of parentheses, (), and a body between braces, {}. Two of the components of a method declaration comprise the method signature - the method'sname and the parameter types. More generally, method declarations have six components, in order: Modifiers - such as public, private, and others you will learn about later. The return type - the data type of the value returned by the method, but void method does notreturn a value to calling method. UNIT-I II B.Tech. I SEM (R22) The method name - the rules for field names apply to method names as well, but the convention is a little different. The parameter list in parenthesis - a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses(). Ex: int add(int a,int b) { } or int add() { } The method body, enclosed between braces - the method's code, including the declaration of local variables, goes here. { //body of amethod } Naming a Method Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multiword names, the first letter of each of the second and following words should be capitalized. Here are some examples: run run Fast getBackgro und getFinalDat a Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading. Overloading Methods The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance"). In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list. Overloaded methods are differentiated by the number and the type of the arguments passed intothe method. You cannot declare more than one method with the same name and the same number and typeof arguments, because the compiler cannot tell them apart. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. Overloaded methods should be used sparingly, as they can make code much less readable. 3) Classes In object-oriented terms, we say that your bicycle is an instance of the class of objects knownas bicycles. A class is the blueprint from which individual objects are created. Java classes contain fields and methods. A field is like a C++ data member, and a method is like a C++ member function. In Java, each class will be in its own.java file. Each field and method has an access level: UNIT-I II B.Tech. I SEM (R22) private: accessible only in this class. (package): accessible only in this package. protected: accessible only in this package and in all subclasses of this class. public: accessible everywhere this class is available. Each class has one of two possible access levels: (package): class objects can only be declared and manipulated by code in this package. Public: class objects can be declared and manipulated by code in any package. Object: Object-oriented programming involves inheritance. In Java, all classes (built-in or user-defined) are (implicitly) subclasses of Object. Using an array of Object in the List class allows any kind of Object (an instance of any class) to be stored in the list. However, primitive types (int, char, etc) cannot be stored in the list. A method should be made static when it does not access any of the non-static fields of theclass, and does not call any non-static methods. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Current states of a class‗s corresponding object are stored in the object‗s instance variables. Creating a class: A class is created in the following wayClass { Member variables; Methods; } An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner. Class Variables – Static Fields We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that classexist. It is declared using static keyword. Class Methods – Static Methods Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. UNIT-I II B.Tech. I SEM (R22) For example, methods in the java.lang.Math package are class methods. You cannot call nonstatic methods from inside a static method. Bundling code into individual software objects provides a number of benefits, including: Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine. An instance or an object for a class is created in the following way =new (); Encapsulation: Encapsulation is the mechanism that binds together code and the data it manipulates, andkeeps both safe from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and datafrom being arbitrarily accessed by other code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well- definedinterface. To relate this to the real world, consider the automatic transmission on an automobile. It encapsulates hundreds of bits of information about your engine, such as how much we are accelerating, the pitch of the surface we are on, and the position of the shift. The power of encapsulated code is that everyone knows how to access it and thus can use itregardless of the implementation details—and without fear of unexpected side effects. Polymorphism: Polymorphism (from the Greek, meaning ―many forms‖) is a feature that allows one interface tobe used for a general class of actions (One in many forms). The specific action is determined by the exact nature of the situation. Consider a stack (which is a last-in, first-out list). We might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. In Java we can specify a general set of stack routines that all share the same names. UNIT-I II B.Tech. I SEM (R22) More generally, the concept of polymorphism is often expressed by the phrase - one interface, multiple methods. This means that it is possible to design a generic interface to a group of relatedactivities. This helps reduce complexity by allowing the same interface to be used to specify a generalclass of action. Polymorphism allows us to create clean, sensible, readable, and resilient code. 4) Inheritance or class Hierarchies: Object-oriented programming allows classes to inherit commonly used state and behavior fromother classes. Different kinds of objects often have a certain amount in common with each other. In the Java programming language, each class is allowed to have one direct superclass, andeach superclass has the potential for an unlimited number of subclasses. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. In this example, Bicycle now becomes the super class of Mountain Bike, Road Bike, and Tandem Bike. The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class extends { // new fields and methods defining a sub class would go here } The different types of inheritance are: 1. Single level Inheritance. 2. Multilevel Inheritance. 3. Hierarchical inheritance. 4. Multiple inheritance. 5. Hybrid inheritance. Multiple, hybrid inheritance is not used in the way as other inheritances but it needs a specialconcept called interfaces. 5) Method Binding: Binding denotes association of a name with a class. Static binding is a binding in which the class association is made during compile time.This is also called as early binding. Dynamic binding is a binding in which the class association is not made until the object iscreated at execution time. It is also called as late binding. UNIT-I II B.Tech. I SEM (R22) Abstraction: Abstraction in Java or Object oriented programming is a way to segregate/hiding implementation from interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class and Object. An essential component of object oriented programming is Abstraction. Humans manage complexity through abstraction. For example people do not think a car as a set of tens and thousands of individual parts. Theythink of it as a well defined object with its own unique behavior. This abstraction allows people to use a car ignoring all details of how the engine, transmissionand braking systems work. In computer programs the data from a traditional process oriented program can be transformedby abstraction into its component objects. A sequence of process steps can become a collection of messages between these objects. Thuseach object describes its own behavior. Overriding: In a class hierarchy when a sub class has the same name and type signature as a method in thesuper class, then the method in the subclass is said to override the method in the super class. When an overridden method is called from within a sub class, it will always refer to the versionof that method defined by the sub class. The version of the method defined by the super class will be hidden. Exceptions: An exception is an abnormal condition that arises in a code sequence at run time. In otherwords an exception is a run time error. A java exception is an object that describes an exceptional condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. 6) Summary of OOP concepts OOP) is a programming paradigm that represents concepts as "objects" that have data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are usually instances of classes, are used to interact with one another to designapplications and computer programs. Object-oriented programming is an approach to designing modular, reusable software systems. The goals of object-oriented programming are: ✓ Increased understanding ✓ Ease of maintenance ✓ Ease of evolution. ✓ Object orientation eases maintenance by the use of encapsulation and information hiding. UNIT-I II B.Tech. I SEM (R22) 7) Object-Oriented Programming – Summary of Key Terms Definitions of some of the key concepts in Object Oriented Programming (OOP) Term Definition Abstract Data Type A user-defined data type, including both attributes (its state) andmethods (its behavior). Aggregation Objects that are made up of other objects are known as aggregations. The relationship is generally of one of two types: Composition – the object is composed of other objects. This form of aggregation is a form of code reuse. E.g. A Car is composed of Wheels, a Chassis and an Engine Collection – the object contains other objects. E.g. a List contains several Items; A Set several Members. Attribute A characteristic of an object. Collectively the attributes of an object describe its state. E.g. a Car may have attributes of Speed, Direction, Registration Number and Driver. Class The definition of objects of the same abstract data type. In Java class is the keyword used to define new types. Encapsulation The combining together of attributes (data) and methods (behavior/processes) into a single abstract data type with a public interface and a private implementation. This allows theimplementation to be altered without affecting the interface. Inheritance Acquiring the properties from base class to derived class. The first class is often referred to the base or parent class. The child is often referred to as a derived or sub-class. Inheritance is one form of object-oriented code reuse. E.g. Both Motorbikes and Cars are kinds of Motor Vehicles and therefore share some common attributes and behaviour but mayadd their own that are unique to that particular type. Interface The behaviour that a class exposes to the outside world; its public face. Also called its contract‗. In Java interface is also a keyword similar to class. However a Java interface contains no implementation: simply describes the behavior of an Object. Member Variable A characteristic of an object or See attribute Method The implementation of some behaviour of an object. Message The invoking of a method of an object. In OOPs objects send each other messages to achieve the desired behaviour. Object An instance of a class. Objects have state, identity and behaviour. Overloading Allowing the same method name to be used for more than one implementation. The different versions of the method vary according to their parameter lists. If this can be determined at compile time then static binding is used, otherwise dynamic binding is used to select the correct method as runtime. UNIT-I II B.Tech. I SEM (R22) Polymorphism Generally, the ability of different classes of object to respond to the same message in different, class-specific ways. Polymorphic methods are used which have one name but different implementations for different classes. E.g. Both the Plane and Car types might be able to respond to a turnLeft message. While the behaviour is the same, the means of achieving it are specific to each type. Primitive Type The basic types which are provided with a given object orientedprogramming language. E.g. int, float, double, char, Boolean Static(Early) Binding The identification at compile time of which version of a polymorphic method is being called. In order to do this thecompiler must identify the class of an object. Dynamic (Late) Binding The identification at run time. When the class of an object cannot be identified at compile time, so dynamic binding must be used. 8) Advantage of OOPs over Procedure-oriented programming language OOPs makes development and maintenance easier where as in Procedure- orientedprogramming language it is not easy to manage if code grows as project size grows. OOP provides data hiding whereas in Procedure-oriented programming language a globaldata can be accessed from anywhere. OOP provides ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language. Procedure Oriented Programming Object Oriented Programming In POP, program is divided into small parts In OOP, program is divided into parts called functions called objects Importance is not given to data but Importance is given to the data rather than tofunctions as well as sequence procedures or functions because it works of actions to be asa real world done. POP follows Top Down approach. OOP follows Bottom Up approach. POP does not have any access specifier. OOP has access specifiers Public, Private, Protected, etc. In POP, Data can move freely from function In OOP, objects can move and to function in the system. communicatewith each other through member functions. To add new data and function in POP is not so OOP provides an easy way to add new data and easy (Project grows) function. POP does not have any proper way for hiding OOP provides Data Hiding so provides more data so it is less security secure In POP, Overloading is not possible. Overloading is possible in the form of Function Overloading and Operator Overloading. Most function uses Global data for sharing Data cannot move easily from function to that can be accessed freely from function function, it can be kept public or private so tofunction in the system. wecan control the access of data. UNIT-I II B.Tech. I SEM (R22) Example of POP are: C, VB, Pascal, etc. Example OOP: C++, JAVA, VB.NET, C#.NET. 9) Java Basics: History of JAVA Java is a high level programming Language. It was introduced by ―SUN Microsystems‖ in June 1995. It was developed by a team under James Gosling. Its original name was ―OAK‖ and later renamed to Java. Java has become the standard for Internet applications. Since the Internet consists of different types of computers and operating systems. A commonlanguage needed to enable computers. To run programs that run on multiple plot forms. Java is Object-Oriented language built on C and C++. It derives its syntax from C and its Object-Oriented features are influenced by C++. Java can be used to create two types of programs Applications Applets. An application is a prg.that runs on the user‘s computers under the operating system. An Applet is a small window based prg.that runs on HTML page using a java enabled web browser like internet Explorer, Netscape Navigator or an Applet Viewer. The Java Programming Environment Applets are java programs. That run as part of a web page and they depend on a web browser in order to run. Applications are programs that are stored on the user‘s system and they do not need a web browser in order to run. The Java programming environment includes a number of development tools to develop applet and application. The development tools are part of the system known as “Java Development Kit” or “ JDK”. The JDK include the following. 1. Packages that contain classes. 2. Compiler 3. Debugger JDK (java development tool kit): It is a software package from the sun micro systems where a new package JFC( java foundationclasses) was available as a separate package JDK provides tools in the bin directory of JDK and they are as follows: Javac: Javac is the java compiler that translates the source code to byte codes. That is, itconverts the source file. Namely the.java file to.class file. Java: The java interpreter which runs applets and Applications by reading and interpreting thebyte code files. That is, it executes the.class file. Javadoc: Javadoc is the utility used to produce documentation for the classes from the java files. JDB: JDB is a debugging tool. The way these tools are applied to build and run application programs is as follows: The source code file is created using a text editor and saved with a.java (with Extension). The source code is compiled using the java compiler javac. This translates source code to byte codes. The compiled code is executed using the java interpreter java. UNIT-I II B.Tech. I SEM (R22) JVM (JAVA VIRTUAL MACHINE) Java is both compiled and an interpreted lang. First the java compiler translates source code into the byte code instructions. In the next stage the java interpreter converts the byte code instructions to machine code. This machine within the computer‘ is known as the “Java Virtual Machine” or JVM. The JVM can be thought as a mini operating system that forms a layer of abstraction where the underlying hardware. The portability feature of the.class file helps in the execution of the prg on any computer with the java virtual machine. This helps in implementing the “write once and run anywhere” feature of java. JAVA RUNTIME ENVIRONMENT JRE consists of the java virtual machine. The java plot form core classes and supporting files. Itis the run time part of the java Development Kit. No compiler, no debugger, no tools. Loding the.class files: Performed by the ‗ class loader‘. Verifying bytecode: Performed by the ‗ bytecode verifier‘.Executing the code : Performed by the runtime interpreter. JIT (JUST – IN – TIME) Just – In – Time (JIT) compiler is a program that runs java bytecode into instructions that can besent directly to the processor. (Machine code). Steps to execute a java prg: ? Open any editor such as notepad ? Type the source code ? Save it with.java extension (File Name and class name must be same) ? Compile it ? Run it UNIT-I II B.Tech. I SEM (R22) Steps to compile a java prg: ? Open Dos prompt ? Set the path Ex: path=c:\jdk1.2.2\bin and press enter key ? Move to your working directory/folder ? Compile the prg Ex: javac filename.java ? Run the prg Ex: java filename IN THE JAVA PROGRAM: public: It indicates that main() can be called outside the class. static: It is an access specifier, which indicates that main() can be called directly withoutcreating an object to the class. void: It indicates that the method main() doesn‘ t return a value. main(): It is a method which is an entry point into the java prg. When you run a java prg.main()is called first. String args [ ]: String is a class, which belongs to java.lang package. It can be used as a stringdata type in java. args[]: It is an array of string type. It is used to store command line args. System: It is a class, which belongs to java.lang package. out: It is an output stream object, which is a member of System class. println(): It is a method supported by the output stream object ―out‖. It is used to display any kindof output on the screen. It gives a new line after printing the output. print(): It is similar to println(). But doesn‘ t give a new line after printing the output. Java‟s Byte code: The key that allows java to solve the both security and portability problems is that the output of a java compiler is not executable code rather it is byte code. Byte code is highly optimized set of instructions designed to be executed by java runtime systems, which is called JVM. Byte codes are instructions that are generated for a virtual machine. A virtual machine is a program that processes these generalized instructions to machine specific code. 10) Differences of JAVA from C++ No typedefs, defines or preprocessors No header files No structures and unions No enums (enum class is there) No functions – only methods in classes No multiple inhehitance trough class (achieve using interface) No operator overloading (except ‗+‘ for string concatenation) No automatic type conversions (except for primitive types) No pointers UNIT-I II B.Tech. I SEM (R22) 11) Java Buzzwords or Features of Java: No discussion of the genesis of Java is complete without a look at the Java buzzwords. Although the fundamental forces that necessitated the invention of Java are portability and security, other factors also played an important role in mol ding the final form of the language. The key considerations were summed up by the Java team in the following list of buzzwords: 1. Simple: Java follows the syntax of C and Object Oriented principles of C++. It eliminates thecomplexities of C and C++. Therefore, Java has been made simple. 2. Object-Oriented: It is an Object-Oriented programming language. The object model in Java is simple. Although influenced by its procedures. It was designed to be source code compatible with any other language. 3. Plot form Independent: Plot form is the combination of operating system and microprocessor. Java programming works in all plot forms. It is achieved by JVM (Java Virtual Machine). The philosophy of java is ―Write Once, Run anywhere‖ (WORA). 4. Robust: Java is strictly a typed language. It has both a compiler and an interpreter. Compiler checks code at run time and garbage collection is taking care of by java automatically. Thus it isa robust language. 5. Secure: java developers have taken all care to make it a secure programming language. For Ex. Java Applets are restricted from Disk I/O of local machine. 6. Distributed: Java is designed for the distributed environment of the Internet. It handles TCP/IP protocols. Java‘s remote method invocation (RMI) make distributed programming Possible. UNIT-I II B.Tech. I SEM (R22) 7. Multithreaded: Java was designed to meet the real-world requirement. To achieve this, javasupports multithreaded programming. It is the ability to run any things simultaneously. 8. Dynamic: That is run time. This makes it possible to dynamically link code in a safe andsecure manner. 9. Architecture-Neutral A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it willrun tomorrow—even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java Virtual Machine (JVM) in an attempt to alter this situation. Their goal was ―write once; run anywhere, anytime, forever. 10. Interpreted and High Performance Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java byte code. This code can be interpreted on any system that provides a Java Virtual Machine. It would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. Comments: There are 3 types of comments defined by java. Those are Single line comment, multilane comment and the third type is called documentation comment. This type of comment isused to produce an HTML file that documents your prg. // this is single line comment. Key words: Keywords are the words. Those have specifics meaning in the compiler. Those are called keywords. There are 49 reserved keywords currently defined in the java language. Thesekeywords cannot be used as names for a variable, class or method. Those are, Java Is a Strongly Typed Language It is important to state at the outset that Java is a strongly typed language. Indeed, part of Java‘ssafety and robustness comes from this fact. Let‘s see what this means. UNIT-I II B.Tech. I SEM (R22) First, every variable has a type, every expression has a type, & every type is strictly defined. Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as insome languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class. For example, in C/C++ you can assign a floating-point value to an integer as shown below int n=12.345; where in the above case the integer variable holds only the round part of the assigned fractionvalue as n=12. In Java, you cannot. Also, in C there is not necessarily strong type-checking between aparameter and an argument. In Java, there is. 12) DATA TYPES: The data, which gives to the computer in different types, are called Data Types or Storage representation of a variable is called Data Type. Java defines 8 types of data: byte, short, int, long, float, double, char and Boolean. These can be put in Four types: Integer: this group includes byte, short, int & long, which are whole valued signed numbers. Floating-point numbers: float & double, which represents numbers with fractional precision.Character: This represents symbols in a character set, like letters and numbers. Boolean: This is a special type for representing true / false values. Examples of double and char class FindSqrt class CharDemo { { public static void main(String args[]) { public static void main(String args[]) char ch1, ch2; { ch1 = 88; // code for X double d1=25,d2=34; ch2 = 'Y'; System.out.println("Sqrt of d1 System.out.print("ch1 and ch2: "); is:"+Math.sqrt(d1)); System.out.println(ch1 + " " + ch2); System.out.println("Sqrt of d2 } is:"+Math.sqrt(d2)); } } This program displays the following output: } ch1 and ch2: X Y UNIT-I II B.Tech. I SEM (R22) Examples of boolean class BoolTest b = false; { if(b) { public static void main(String args[]) System.out.println("This is not executed.");} { System.out.println("10 > 9 is " + (10 > 9)); boolean } b;b = } false; Output: System.out.println("b is " + b); b is false b = true; b is true System.out.println("b is " + b); This is executed. if(b){ 10 > 9 is true System.out.println("This is executed."); } Variables: The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. In Java, all variables must be declared beforethey can be used. The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value]...]; Ex: int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi.char x = 'x'; // the variable x has the value 'x'. Constant identifiers: Final keyword is used for constants. Constant identifiers consist of all capital letters. Internalwords are separated by an underscore (_). Example: final double TAX_RATE =.05 13) The Scope and Lifetime of Variables: All of the variables used till now have been declared at the start of the main( ) method. However, Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Most other computer languages define two general categories of scopes: global and local.The scope defined by a method begins with its opening curly brace. Objects declared in the outer scope will be visible to code within the inner scope. However, thereverse is not true. Objects declared within the inner scope will not be visible outside it. To understand the effect of nested scopes, consider the following program: // demonstrate block if(x == 10) scope.class Scope { // start new scope { int y = 20; // known only to this block public static void main(String args[]) { // x and y both known here. int x; // code within System.out.print("x and y:" +x+ " " + y);x mainx = 10; = y * 2; UNIT-I II B.Tech. I SEM (R22) } } y = 100; // Error! y not known here } // x is still known here. Output: x and y: 10 20 x is 40 System.out.print("\tx is " + x); Types of variables: Java has 4 different kinds of variables local variables parameter variables class variables instance variables Local variables: A local variable will exists as long as the method in which they have been created is still runningAs soon as the method terminates, all the local variables inside the method are destroyed. Example: Scope of local variables: class SomeClass class Scope2 { { public static void main(String args[]) public static void main(String args[ ]) { { void show(){ double x; double …………… Local variables r;r=3.14; int y; } } System.out.println(r ); //Causes error is not } } accessible outside the block } Non-overlapping (or disjoint) scopes: It is possible to declare two variables with the same name in two different block scopes as shownbelow class Scope { public static void main(String args[]) { ------- { double r; { String r; } } } } Parameter variables: A parameter variable is used to store information that is being passed from the location of themethod call into the method that is called. class ToolBox { a=1.0 b=2.0 public static double min(double a,double b) //Parameter variables { ……………….. } } class MyProgram { UNIT-I II B.Tech. I SEM (R22) public static void main(String args[]) {double r; r=ToolBox.min(1.0,2.0); } } Life and scope of parameter variable: The life time of a parameter variable is the entire body of the method A parameter variable behaves like a local variable that is defined at the Start of the method 14) Class variables: Variables that are declared with the keyword static are called as class variables Life of class variables: Class variables exists for the entire execution of the java program Scope of class variables: The scope can be publicclass StaticData { static int a=10,b=20; //Access these variables through class name, because of static. } class StaticDemo { public static void main(String args[]) { int sum=StaticData.a+StaticData.b; System.out.println("sum is"+sum); } } Instance variables: Non static variables that are declared inside a class are called as instance variables.class StaticData { int a=10,b=20; //instance variables of StaticData class } Life and scope of Instance variables: It is limited only the object specified upon the class 15) Literals Integer Literals Integers are probably the most commonly used type in the typical program. Any hole numbervalue is an integer literal. Examples are 1, 2, 3, and 42. Integer literals are classified into three types as Decimal literal Octal literal Hexadecimal literal Decimal literals These are all decimal values, meaning they are describing a base 10 number. There are two otherbases which can be used in integer literals Example: int n=10; UNIT-I II B.Tech. I SEM (R22) Octal literals Octal (base eight). Octal values are denoted in Java by a leading zero. Normal decimal numberscannot have a leading zero. Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of octal‟s 0 to 7 range.Example: int n=07; Hexadecimal literals: Hexadecimal (base 16), A more common base for numbers used by programmers is hexadecimal, which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15. Example: int n=0xfff; Example Program: UNIT-I II B.Tech. I SEM (R22) class Literal { public static void main(String args[]) { int dec=10,oct=07,hex=0xff; System.out.print("decimal literal is:"+dec);System.out.println("octal literal is:"+oct); System.out.println("hexadecimal is:"+hex); } } Floating-Point Literals Floating-point numbers represent decimal values with a fractional component. Example: float f=12.346f (or) 12.346F; double d=34.5678d (or) 34.5678D; Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, trueand false. The true literal in Java does not equal 1, nor does the false literal equal 0. Character Literals Escape Sequence Meaning \n new line Characters in Java are indices into the Unicode \t horizontal tab character set. They are 16-bit values. A literal \v vertical tab character is represented inside a pair of single \b Backspace quotes. All of the visible ASCII characters can be \r carriage return directly entered inside the quotes, such as ‗a‘, \f form feed ‗z‘, and ‗@‘. \a Bell \\ text literal \' ' char literal String Literals \" " String literal String literals in Java are enclosing a \ddd Octal character(ddd) sequence ofcharacters between a pair of \uxxxx Hexa character (xxxx) double quotes. Ex: ―Hello World‖ ―two\nlines‖ ―\‖This is in quotes\‖‖ UNIT-I II B.Tech. I SEM (R22) 16) Java Naming conventions Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method etc. But, it is not forced to follow. So, it is known as convention not rule. All the classes, interfaces, packages, methods and fields of java programming language are givenaccording to java naming convention. Advantage of naming conventions in java By using standard Java naming conventions, you make your code easier to read for yourself andfor other programmers. Readability of Java program is very important. Name Convention class name Should start with uppercase letter and be a noun e.g. String, Color,Button, System, Thread etc. Ex: class MyClass interface name Should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc. method name Should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc. variable name Should start with lowercase letter e.g. firstName, orderNumber etc. package name Should be in lowercase letter e.g. package java.lang; constants name Should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc. e.g. final double TAX_RATE =.05 Camel Case in java naming conventions Java follows camelcase syntax for naming the class, interface, method and variable. If name iscombined with two words, second word will start with uppercase letter always. e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc. 17) OPERATORS: Operator is a Symbol. Java provides a rich set of operators as The Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used inalgebra. The arithmetic operators are: + - * / % The Relational Operators: It tells the relationship b/w two operands e.g., a>b, a (greater than),< (less than),>= (greater than or equal to),> 2 will give 15 which is 1111 Shift right zero fill operator : >>> (zero fill right shift) It is moved right by the number of bits specified by the right operand and shifted values arefilled up with zeros. Example: A >>>2 will give 15 which is 0000 1111 The Logical Operators: Logical AND operator: && (logical and) If both the operands are non-zero, then the condition becomes true. Example (A && B) is false. (0 && 1) or (1 && 0) or (0 && 0) is false & (1 && 1) is true Logical OR Operator: || (logical or) If any of the two operands are non-zero, then the condition becomes true. Example (A || B) is true. (0 || 1) or (1 || 0) or (1 || 1) is true & (0 || 0) is false Logical NOT Operator: ! (logical not) Use to reverses the logical state of its operand. If a condition is true then Logical NOToperator will make false. Example !(A && B) is true. instanceof Operator: Type comparision operator This operator is used only for object reference variables. The operator checks whether the objectis of a particular type (class type or interface type). instanceof operator is written as: ( Object reference variable ) instanceof (class/interface type) public class Test { public static void main(String args[]) { String name = "James"; boolean result = name instanceof String;System.out.println( result ); } } Op: James Unary operators: + - ++ - - ! sizeof UNIT-I II B.Tech. I SEM (R22) 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 operator is to decide which value should be assigned to the variable. The operator is written as: variable x = (expression)? value if true : value if false int x = (10>20)? 100 : 200 Operator Precedence: Expressions: An expression is a construct made up of variables, operators, and method invocations, which areconstructed according to the syntax of the language that evaluates to a single value. int a = 0; arr = 100; System.out.println("Element 1 at index 0: " + arr);int result = 1 + 2; // result is now 3 Statements Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). Ex: System.out.print(A+B); 18) Type Conversion and Casting: We can assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable. However, not all types are compatible, and thus, not all type conversions are implicitly allowed. For instance, there is no conversion defined from double to byte. But it is possible for conversion between incompatible types. To do so, you must use a cast,which performs an explicit conversion between incompatible types. Java„s Automatic Conversions When one type of data is assigned to another type of variable, an automatic type conversion willtake place if the following two conditions are satisfied: The two types are compatible. The destination type is larger than the source type. UNIT-I II B.Tech. I SEM (R22) When these two conditions are met, a widening conversion (Small data type to Big data type) takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required. For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, the numeric types are not compatible with char or boolean. Also, char and boolean are not compatible with each other. Java also performs an automatic type conversion when storing a literal integer constant intovariables of type byte, short, or long. Casting Incompatible Types The automatic type conversions are helpful, they will not fulfill all needs. For example, if we want to assign an int value to a byte variable. This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type. To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form: (target-type) value Here, target-type specifies the desired type to convert the specified value to. Example: int a; byt e b; b = (byte) a; A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. As integers do not have fractional components so, when a floating- point value is assigned to an integer type, the fractional component is lost. Example Program: Conversion.java class Conversion { public static void main(String args[]) {byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte.");b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int.");i = (int) d; System.out.println("d } and i " + d + " " + i); System.out.println("\nConversion of double to byte.");b = (byte) d; UNIT-I II B.Tech. I SEM (R22) System.out.println("d and b " + d + " " + b); } The Type Promotion Rules Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte, short, and char values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double. Ex: class Promote { double d =.1234; public static void main(String args[]) { double result = (f * b) + (i / c) - (d * s); byte b = 42; System.out.println((f * b) + " + " + (i / c) + " char c = 'a'; - " + (d * s)); short s = 1024; System.out.println("result = " + result); int i = 50000; } float f = 5.67f; } Let‟s look closely at the type promotions that occur in this line from the program: double result = (f * b) + (i / c) - (d * s); In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in d*s, the value of s is promoted to double, and the type of the sub expression is double. 19) Control Statements or Control Flow: IF Statement The IF statement is Java‘s conditional branch statement. It can be used to route programexecution through two different paths. The general form of the if statement: if (condition) statement1; Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is any expression that returns a Boolean value. If the condition is true, then statement1 is executed. IF –ELSE Statement If the condition is true, then statement1 is executed. Otherwise statement2 is executed. The general form of the if statement: if (condition) statement1;else statement2; } UNIT-I II B.Tech. I SEM (R22) The if-then-else statement provides a secondary path of execution when an "if" clause evaluatesto false. void ifClause() { int a, b; if(a < b) a = 0; else b = 0; } UNIT-I II B.Tech. I SEM (R22) Nested ifs A nested if is an if statement that is the target of another if or else. Here is an example:if(i == 10) { if(j < 20)a = b; if(k > 100) c = d; // this if iselse a = c; // associated with this else } else a = d; // this else refers to if(i == 10) The if-else-if Ladder A common programming construct that is based upon a sequence of nested ifs is the if- else-ifladder. It looks like this: if(conditi on) stateme nt; else if(condition) statement; else if(condition) statement; else state ment; Example: // Demonstrate if-else-if statements. class IfElse { public static void main(String args[]) { int month = 4; // AprilString season; if(month == 12 || month == 1 || month == 2)season = "Winter"; else if(month == 3 || month == 4 || month == 5) season = "Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 || month == 10 || month == 11) season = "Autumn"; else UNIT-I II B.Tech. I SEM (R22) season = "Bogus Month"; System.out.println("April is in the " + season + "."); } } Output: April is in the Spring. The switch Statement Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types. Program: displays the name of the month, based on the value of month, using the switchstatement. class SwitchDemo { public static void main(String[] args) {int month = 8; switch (month) { case 1: System.out.println("January");break; case 2: System.out.println("February"); break; case 3: System.out.println("March");break; case 4: System.out.println("April");break; case 5: System.out.println("May");break; case 6: System.out.println("June");break; case 7: System.out.println("July");break; case 8: System.out.println("August");break; case 9: System.out.println("September");break; case 10: System.out.println("October");break; case 11: System.out.println("November");break; case 12: System.out.println("December");break; default: System.out.println("Invalidmonth."); break; } } } Output:"August" UNIT-I II B.Tech. I SEM (R22) Iteration Statements Java‘s iteration statements are for, while, and do-while. These statements create what we commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. The while Statement The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { Statements // body of loop } Note: The while statement evaluates an expression, which must return a Boolean value. Ex: class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count);count++; } } } Output: Count is:1 Count is:2.................. Count is:10 do-while statement The do-while loop always executes its body at least once, because its conditional expression is atthe bottom of the loop. Its syntax can be expressed as: do { statement(s) } while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once and while terminates with semicolon. Ex Program: class DoWhileDemo { public static void main(String[] args){int count = 1; do { System.out.println("Count is: " + count);count++; UNIT-I II B.Tech. I SEM (R22) } while (count < 11); } } Output: Count is:1 Count is:2.................. Count is:10 The for Statement The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:for (initialization; termination; increment) { statement(s) } Ex: class ForTick { public static void main(String args[]) {for(int n=10; n>0; n--) System.out.println("tick " + n); } } When using the for statement, we need to remember that The initialization expression initializes the loop; it's executed once, as the loop begins. When the termination expression evaluates to false, the loop terminates. The increment expression is invoked after each iteration through the loop; it is perfectlyacceptable for this expression to increment or decrement a value. // Without using the comma. // Using the comma. class Sample { class Comma { public static void main(String args[]) { public static void main(String args[]) { int a, b; int a, b; b = 4; for(a=1, b=4; a