Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 B. Sc Computer Science Subject : Internet and Java Programming Unit : II Semester : 6 Unit – II - OBJECT ORIENTED FUNDAMENTALS AND JAVA REVOLUTION Object oriented programming – Encapsulation – Inheritance – Polymorphism – Java Genesis – Characteristics – Java Programming techniques – Reserved words – Identifiers – Literals – Operators – Separators – Variables – Types – Arrays – Operator Precedence OBJECT ORIENTED PROGRAMMING. Object Oriented Programming is a method of implementation in which programs are organized as a collection of objects each of which represents an instance of some class. TWO PARADIGMS OF OBJECT ORIENTED PROGRAMMING All programs consists of two elements code and data. A program can be conceptually organized around its code or around the data. The process – oriented approach or model characterizes a program as a series of linear steps . This approach can be thought of as code acting on data. Procedural languages like C employ this model to considerable success. Problems with model appear as programs grow larger and complex. To manage the increasing complexity the second approach called object – oriented programming was conceived. Object oriented programming organizes a program around its data and a set of well defined interfaces to that data. An object oriented program can be characterized as data controlling access to code. ABSTRACTION Humans manage complexity through abstraction. For ex, people do not think of a car as a set of individual parts. They think of it as a well defined object. This abstraction allows people to drive a car without being overwhelmed by its complexity. They can ignore the details of how the engine, braking systems work. A powerful way to manage abstraction is through the use of hierarchical classifications. The data from a traditional process- oriented program can be transformed by abstraction into its components. A sequence of process steps can become a collection of messages between these objects. Each of these objects describes its own behavior. These objects are treated as concrete entities that respond to messages telling them to do something. This is the essence of object-oriented programming. OOP PRINCIPLES ENCAPSULATION It is the process of localizing data definition, i.e. of binding together (wrapping) code and data specifically related to a single entity to form a logical unit called a class. This mechanism keeps the data safe from outside interference and misuse. Encapsulation is a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. The basis of encapsulation is the ‘class’. Object is an instance of a class. Class is a logical construct and object is a physical reality. The code and data within a class are called as members of the class. The data are referred to as the instance variables or member variables. The code that access or operate the data are referred to as member methods or methods. Each method in a class may be marked as private or public. The public interface of a class represents everything that a external user can know. The private methods and data can only be accessed by code that is a member of the class. So any other code that is not a member of a class cannot access a private method or variable. 2 INHERITANCE Inheritance is the ability of a class to acquire the characteristics and behavior i.e. nothing but the properties another class. The most common method of using inheritance is to create class hierarchies that move from the most general concept to the most specific representation. The class that inherits the properties from other is called the derived class or subclass and the one from which it is derived is called the base class or the super class. Each subclass has an “is a relationship” to its super class. Transportation Public Bus Plane Transport Train Private Transport Automobile Motorcycle Yamaha Honda In the above example, Yamaha is a bike. A bike is a private transport. A private transport ‘is a ‘ form of transportation. POLYMORPHISM Polymorphism is a feature that allows one interface to be used for a general class of actions. Ie a concrete operation inherits its definition and properties from a generic operation. It allows a method to have multiple implementations that are selected based on the type of the object that is passed to the method invocation. i.e. one interface multiple methods. Consider a stack. You might have a program that requires three types of stacks. One stack is used for integers, 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 a procedural language, you have to create three different sets of stack routines, with each set using different name. With polymorphism, you can specify a general set of stack routines that all share the same names. JAVA GENESIS Java is related to C++. Much of the character of Java is inherited from c, and c++. Java derives its syntax from c and many of its object-oriented features from c++. Java was influenced by C++ and not an enhanced version of C++. Java was conceived by James Gosling, Patrick Noughton, Chris Wrath, Ed Frank and Mike Sheridan at Sun Microsystems in 1991. It took 18 months to develop the first working version. The language was initially called Oak but was renamed Java in 1995. The primary motivation was the need for a platform-independent language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. A Java compiler converts the Java source code into a binary program consisting of byte codes. Byte codes are optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). JVM is an interpreted for byte code. This interpreter inspects and deciphers the byte codes and executes the actions that the byte codes specify. A Java interpreter can run stand-alone or it can be a part of a web browser such as Netscape Navigator or IE where it can be invoked automatically to run applets in a web page. 3 Translating a Java program into byte code makes it easier to run a program in a wide variety of environments. Only JVM needs to be implemented for each platform. Although the details of JVM differ from platform to platform, all interpret the same Java byte code. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPU connected to the Internet. When a program is interpreted, it generally runs substantially slower than it would run if compiled to executable code. However with Java, the difference is not great. The use of byte code enables the Java run-time system to execute program much faster than you might expect. Sun has just completed its Just In Time (JIT) compiler for byte code, which is included in Java 2. JIT is a part of JVM, it compiles the byte code into executable code in real time. It is not possible to compile a entire Java program into executable code all at once, as Java performs various run-time checks that can be done only at run time. Instead JIT compiles the code as needed only during execution. JAVA CHARACTERISTICS Simple – Java removes many c, c++ features that were either redundant, sources of confusion, i.e. no use of pointers, no multiple inheritance, no need to explicitly free memory. This has reduced the complexity and has increased the reliability of the language. Robust and secure – Java is robust in its many safeguards to ensure reliable code. 1. There is no Java preprocessor, i.e. the program will execute just as it is written without worry that a variable is #defined to mean something else. 2. Java has strict compile time and runtime checking for the proper use of the type system. 3. Free from numerous memory bugs as it is garbage-collected (explicit deallocation, Garbage collection is a technique that eliminates the need for memory management by periodically reclaiming unused memory) Security features The automatic downloading of program across the insecure Internet made security a high priority for the Java Development Team. 1. The first security feature is that computer memory is not directly accessible by any Java program. 2. Byte codes are verified for accuracy and tested for security violation 3. Java’s network package allows the user to set the level of access for each system. Architecture Neutral If you run a program today there is no assurance that it will execute tomorrow, on the same machine. Operating system upgrades, processor upgrades and changes in core system resources can all collude to make a program cease to function. The Java designers made several hard decisions in the Java Language and runtime so you can truly write once run anywhere. Write a good program and Java will make sure that it works on Macintosh, UNIX etc. Multi- threaded Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this Java supports multithreaded programming which allows you to write programs that do many things simultaneously. Java runtime system supports multi process synchronization which enables you to construct smoothly running interactive systems. Distributed Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. The original version of Java included features for 4 intra-address-space messaging. This allows objects on two different computers to execute procedures remotely. Java has revived these interfaces in a package called ‘Remote Method Invocation (RMI). Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run-time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of byte code may be dynamically updated on a running system. JAVA PROGRAMMING TECHNIQUES A simple Java program can be as follows class Sample{ public static void main(String args[ ]){ System.out.println(“Welcome”); } } The reserved word ‘class’ is used to declare a class. public - main() must be declared public since it must be accessed by code outside of its class when the program is started static – the method can be called independent of an instance of a class, i.e. its not necessary to instantiate the class to invoke the method. void – specifies that the method main() doesn’t return any value String args[ ] declares a parameter named args, which is an array of instances of the class String. Objects of type String store character strings. args[ ] receives any command line arguments . RESERVED WORDS Reserved words are special identifiers, and these keywords can only be used for their intended purpose and cannot be used as an identifier for a variable, class or method name. The Java reserved words are as follows abstract case const else for instanceof new return switch void boolean cast continue extends goto int package short this volatile break catch default final if interface private static throws while byte char do finally implements long protected strictfp transient byvalue class double float import native public synchronized try IDENTIFIERS Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign characters. They must not begin with a number, they should not be confused with a numeric literal. Java is case sensitive so ‘MATRIX’ is a different identifier from ‘matrix’. Some examples of valid identifiers are value b5 $sname dt_of_join 5 Invalid identifiers 8value max-level or/and SEPARATORS The most commonly used separator is semicolon. The other separators are Symbol purpose () Used to specify the list of parameters in method definition and invocation {} To represent the values of initialized arrays. To define a block code for classes, methods and local scopes. [] Use to declare array types. Also used when dereferencing array values. ; semicolon is used to terminate statements , Comma separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a for statement . Period is used to separate package names from subpackages and classes. Also used to separate a variable or method from a reference variable TYPES Java defines eight simple types of data : byte, short, int, long, char, float , double and boolean. These can be put in four groups. Integers - this group includes byte, short, int and long which are for wholevalued signed numbers Floating - point numbers : This includes float and double Characters - this includes char Boolean - this includes boolean, which is a special type for representing true/false values Integers All the four integer types are signed, positive and negative values. Java doesn’t support unsigned, positive-only integers. The width and the range of the integer types can be specified Type width long 64 int 32 short 16 byte 8 Range -9,233,372,036,854,775,808 to 9,233,372,036,854,775,807 -2,147,483,648 to 2,147,483,647 -32,768 to 32,768 -128 to 127 byte- This is a signed 8-bit type that has a range from –128 to 127. The variables of type byte are used when you work with a stream of data from a network or file. The variables can be declared as - byte a ; short - This is a signed 16-bit type that range from -32,768 to 32,768. int - It is a signed 32 bit type that ranges from -2,147,483,648 to 2,147,483,647 long - long is a signed 64 bit type and is useful when an int type is not large enough to hold the desired value. 6 Floating –point types The two kinds of floating point types are float and double which represent single and double precision numbers type double long width 64 bits 32 bits range 1.7e-308 to 1.7e+308 3.4e-038 to 3.4e+038. float - specifies single precision values. Single precision is faster on some processors and takes half as much space as double precision. float can be useful when representing dollars and cents double – It uses 64 bits to store a value. double precision is actually faster than single precision. All mathematic, trigonometric functions such as sqrt(), sin(), cos() return double values. double is the best choice if you need to maintain accuracy. Characters The data type used to store characters is char. Java uses Unicode to represent characters. Unicode defines fully international char set that represents characters of all languages, such as Latin, Greek. Arabic etc. It requires 16 bits. The range of char is 0 to 65536. There are no negative chars. Ex class Chardemo{ public static void main(String args[ ]){ char ch1, ch2; ch1 = 88; ch2 = “Y”; System.out.println(“ch1 and ch2 : ” + ch1+” “+ch2); } } The output is ch1 and ch2 : X Y where 88 is the ASCII value that corresponds to X. Booleans boolean is the type used for logical values. It can have any one of the two possible values true or false. This is the type returned by all relational operators such as a > b. boolean is the type required by conditional expressions that govern the control statements such as if or for. LITERALS Literals are nothing but constants. A literal represents a value of certain type, whereas the type itself describes how the value behaves and how it is stored. The various literals are as follows Integer literals Any integral numeric value is an integer value. Ex are 5, 7 etc. These are decimal values i.e. of base 10. The other two bases used in integral literals are octal and hexadecimal. Octal values are denoted in Java with a leading zero. Decimal numbers cannot have leading zero. A hexadecimal constant can be specified with a leading 0x or 0X. Floating Point literals Floating Point numbers represent decimal values with a fractional component. They can be expressed in two ways Standard notation – use some number followed by a decimal point and then some fractional digit. Ex – 5768.33333333 7 Scientific notation – a standard notation floating point number with a additional notation that indicates a multiplication times ten to the specified exponent. The exponent is given by a E or e followed by decimal number. Ex – 45.34e12, 348e01. Floating point literals in Java default to double precision, you need to append an F or f to force the constant to be small enough to store into a variable declared as a float. Boolean Literals The Boolean literals can have two values i.e. true or false. Character Literals A literal character is represented inside a pair of Parentheses (‘ ‘). For characters that are impossible to enter directly, there are several escape sequences which allow to enter the character such as (‘\’), for the single quote character itself and ‘\n’ for new line character. String literals String literals are arbitrary text enclosed in double quotes. Ex – “name”, “Command”. Java strings must begin and end in the same line. There is no line continuation escape sequence as in other language. ARRAYS Array is a collection of values of the same data type referred by a common value. One-dimensional arrays The general form of one-dimensional array is type var-name[ ]; type is the data type of the each element that comprises the array. Ex – int marks[ ]; marks is a array variable, no array actually exists. The value of marks is set to null. A operator “new” is used to allocated space for an array. marks = new int[6]; marks refers to an array of 6 integers. The individual elements of the array can be accessed starting from the index or subscript 0. For Ex. class Student{ public static void main(String args[ ]){ int marks[ ] = new int[6]; marks[0] = 50; marks[1] = 55; marks[2] = 43; marks[3] = 61; marks[4] = 77; marks[5] = 58; System.out.println(“The marks scored in subject1 is :”+marks[0]); } An array initializer is a list of comma separated expressions surrounded by curly braces. The commas separated the values of the array elements. The array will be created large enough to hold exactly the number of elements you specify in the array initializer. 8 Java strictly checks that you don’t store or reference values outside the range of the array. Java runtime will check to be sure that all array indices are in the correct range. Multi- dimensional arrays These are arrays within arrays. The multidimensional arrays are allocated in blocks. If it is an X by Y by Z three-dimensional matrix, then the storage required will be X times Y times Z times the size of the type stored in each cell. In Java you can declare a variable to be three- dimensional but leave out the second and the thIrd dimension then allocate the Y and Z directions separately. Ex double matrix [ ] [ ] = new double [4] [4]; matrix[0] = new double[4]; matrix[1] = new double[4]; matrix[2] = new double[4]; matrix[3] = {0,1,2,3}; Ex class Exarray{ public static void main(String args[ ]){ int twodim = new int [4] [5]; int I, j, k = 0; for(i = 0; i < 4 ; i++ ){ for(j = 0 ; j<5; j++){ twodim[i][j] = k ; k++; } } for(i = 0; i < 4 ; i++ ){ for(j = 0 ; j<5; j++){ System.out.println( twodim[i][j] ) ; k++; } } } } VARIABLES The variable is the basic unit of storage in Java. A variable is defined by the combination of an identifier, a type and a optional identifier. All variables have a scope, which defines their visibility and a lifetime. Declaring a variable The variables must be declared before using them. The format for declaration is type identifier [= value][, identifier [=value]…] Examples : int a, b, c; int a = 8, b = 7; double x = 49.90; char c = ‘j’; Dynamic initialization The variables can be initialized dynamically, using any expression valid at the time the variable is declared. Class Leng{ public static void main(String args[ ]){ double a = 3.0 , b = 4.0; double c = Math.sqrt(a * a + b * b) ; System.out.println(“ Hypotenuse “ +c); } } a and b are declared as constants, c is initialized dynamically to the length of the hypotenuse. 9 The scope and lifetime of variables A block defines the scope. A scope determines what objects are visible to other parts of the program. It determines the lifetime of those objects. In Java the two major scopes are those defined by a class and those defined by a method. When you declare a variable within a scope, you are localizing the variable and protecting it from unauthorized access and/or modification. Scopes can be nested. Objects declared within inner scope will not be visible outside it. class Scope{ public static void main(String args[ ]){ int x; x = 12; if ( x == 12){ int y = 6; // y is visible only to this block System.out.println(“the value of y :” +y); x = y + 4; } y = 5; // error as y is not visible here System.out.println(“the value of x : +x); } } y is defined within the if block. So its value is not visible outside that block. Within the if block x can be used as code within a block has access to the variables declared by an enclosing scope. Variables are created when their scope is entered, and destroyed when their scope is left. So the variables declared within a method will not hold their values between calls to that method. Type conversion and casting It is common to 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. It is possible to assign a int value to a long variable. Not all types are compatible, so not all type conversions are implicitly allowed. i.e. there is no conversion defined from double to byte. It is possible to get a conversion between incompatible types using the ‘casting’ Automatic conversion Automatic conversion occur under the following conditions 1. The two types are compatible 2. The destination type is larger than the source type A widening conversion takes place when the conditions are met. Numeric types are compatible with each other. The numeric types are incompatible with char or boolean. char and boolean are not compatible with each other. Type casting When you assign an int value to a byte variable the conversion will not be performed automatically as a byte is smaller than an int. The conversion is called a narrowing conversion as you are explicitly making the value narrower to fit into the target type. A cast is a explicit type conversion. The form is (target-type)value The target-type specifies the desired type to convert the specified value to. Ex – int a; byte b; b = (byte) a; 10 Type promotion rules 1. All bytes and short values are promoted to int 2. if one operand is long, the whole expression is promoted to long 3. If one operand is float, the entire expression is promoted to float. 4. If any of the operands is double, the result is double. OPERATORS Operators are characters that instruct the compiler that you wish to perform an operation on some operands. Operators specify operation instructions, while operands are variables, expressions or literal values. Some operators take a single operand these are called unary operators. Some operators come before the operand, these are called prefix operators. And those that come after the operands are called postfix operators. Most operators are between operands and are called as infix binary operators. An operator that takes 3 operands called as ternary operator. The basic types of operators are – arithmetic, bitwise, relational and logical. Arithmetic Operators The operands must be a numeric type, and cannot be used on boolean types. We can use it on char type since char is a subset of int in Java. Four function calculator operators class Calculate{ public static void main(String args[ ]){ int a = 5; int b = a + 2; int c = a * b; int d = c – b; int e = c / d; int f = - b; System.out.println(“value of b =” +b); System.out.println(“value of c =” +c); System.out.println(“value of d =” +d); System.out.println(“value of e =” +e); System.out.println(“value of f =” +f); } } Modulus operator this operator returns the remainder of a division operation. It can be applied to floating-point types as well as integer types. Arithmetic assignment operator The statement is of the form var = var op expression which can be written as var op = expression ie a = a + 5 ; can be written as a + = 5 ; the other operators can be given as a % = 5 ; which is nothing but a = a % 5; a/=7; a * = 10 ; 11 BITWISE LOGICAL OPERATORS Bitwise NOT This is the unary NOT operator ^. which inverts all the bits of its operand . EX the number 18 can be represented in binary as 10010 which becomes 01101 after the NOT operator is applied. Bitwise AND The AND operator (&) produces 1 when both the operands are 1 , 0 zero is produced in all other cases. ex 1010 & 1110 1010 Bitwise OR ( | ) In this case , the result is 1 if any one of the operands is 1. Ex 1010 | 1001 1011 Bitwise XOR ( ^ ) The result is 1 if exactly one operand is 1, else the result is zero. Ex 1110 ^ 1100 1011 Right shift ( >> ) This operator shifts all the bits in a value to the right to a specified number of times. The syntax is value >> num ; Ex int a = 16 ; a = a>>2 ; The result is 4 . ie the binary value of 16 is 10000 which after right shift becomes 00100 . The decimal value of the result is 4. The operator shifts the value of 16 to the right two positions, which causes 2 low – order bits to be lost resulting in number being set to 4. Left shift ( << ) The syntax is value << num ; Ex int a = 64 ; a = a << 2 ; the result is 256. ie the binary value of 64 is 0100 0000 is shifted left two positions, and the result is 1 0000 0000 which is 256. unsigned right shift ( >>> ) >> operator automatically fills two high order bits with its previous contents each time a shift occurs. This preserves the sign of the value. If you are shifting something that doesn’t represent a numeric value, you may not want sign extension to take place. In this case you need to shift a zero to the high order bit no matter what the initial value was. This is known as unsigned shift. Relational operator These operators determine the relationship that one operand has to the other. They determine the equality and the ordering. 12 operators == != > >= < <= equal to not equal to greater than greater than and equal to less than less than and equal to Boolean logical operators They operate on boolean operands. & | ^ || && ! == ?: logical AND logical OR logical XOR short circuit OR short circuit AND logical unary NOT assignment ternary Ternary operator Java includes a special ternary operator(three way ) that can replace certain types of if then else statements. It has the form exp1 ? exp2 : exp3 ie if expression1 is true then expression2 will be evaluated else expression3 will be evaluated OPERATOR PRECEDENCE The precedence or priority of the operators is given as follows Highest () ++ * + >> > == & ^ && || ?: = [] -/ >>> >= != ~ % << < ! <= op= Lowest Square brackets provide the array indexing. The dot operator is used to dereference objects. Using Parentheses Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the result you desire. For ex, consider the following expression a >> b + 3 ; 13 This expression first adds 3 to b and then shifts right by that results. ie. the expression can be written using redundant parentheses like a >>(b + 3 ) ; If you want to first shift right by b positions and then add 3 to that result, you will need to parenthesize like, (a >> b ) + 3 ; QUESTION BANK Give short notes 1. Define object oriented programming. 2. what are three basic principles or features of OOP? 3. Give the difference between OOP and procedure oriented programming. 4. Give examples for Object Oriented Language 5. Define Abstraction 6. Define class. 7. Define object 8. Give the expansion of JVM. what is the work of JVM? 9. What do you mean by bytecode? 10. Give the representation of ternary operator. 11. What was Java initially called? 12. What are the two types of programs that can be created in Java? 13. What do you mean by applet? 14. Give the expansion of JIT 15. How can you justify the robust feature of Java programs 16. What is RMI 17. What do you mean by multiline comment 18. Explain the use of the keywords in the declaration public static void main(String args[ ] ) 19. Give the purpose of the following separators i) {} ii) . 20. What is the name given to Java character set Answer in detail 1. What is encapsulation? 2. Define Inheritance 3. Define Polymorphism. Give examples. 4. What are the differences between C++ and Java 5. Give a note on the data types supported by Java 6. What is Dynamic Initialization 7. Explain Type conversion 8. When do you use type casting 9. Explain multi-dimensional arrays with example 10. Explain bitwise operators in Java 11. Give a note on logical Boolean operators 12. Specify the precedence of operators 13. Write a note on the characteristics of Java 14