


















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
study notes for second year students
Typology: Study notes
1 / 58
This page cannot be seen from the preview
Don't miss anything!



















































It is used to eliminate some of the errors encountered in the procedural approach. It allows us to decompose a problem into number of entities called Objects and then built data and functions around the entities. The combination of data and methods make up an object. Object = data + methods The data of an object can be accessed only by the methods associated with the object. Some of the features of object-oriented paradigm are:
The important object oriented features are namely:
For example a computer is made of various parts such as CPU, Keyboard, and so on. We think it as a single unit, but the single unit has several sub-units. They together do the single task. By assembling sub-parts we can built a single system. It is used to define a data type available in the programming language, called as abstract data type It consists of a set of values and a set of operations. Encapsulation The packing up of data and functions into a single component is known as encapsulation. The data is not reachable by the outside functions. Only those functions that are able to access the data are defined within the class. With encapsulation we accomplish data hiding. Data hiding is an important feature using which an object can be used without the user knowing how it works internally. Fundamental of encapsulation is class. Inheritance It is the method by which objects of one class get the properties of another class. It provides the thought of reusability. The programmer can add new properties to the existing class without changing it. This can be achieved by deriving a new class from the existing one. The new class will possess features of both the classes. For example, re, yellow, and blue are the main colors. The orange is created from the combination of red and yellow, green is created from yellow and blue and violet is created from red and blue. The orange has the attributes of both red and yellow, which produces a new effect. Polymorphism It allows the same function to act in a different way in different classes. It holds an ability to take more than one form. Dynamic Binding Binding means connecting one program to another program that is executed in reply to the call. Dynamic binding is also called as late binding. The code present in the specified program is unknown till it is executed. Message passing The objects communicate with one another. The programming with these objects should be followed with the following steps:
The OOP technology is changing the style of software engineers to think, analyze, plan and implement the software.
Usually a computer language is either compiled or interpreted. Java combines both these approaches thus making Java two-stage system. First, Java compiler translates source code into bytecode instructions. Second, Java interpreter generates machine code that can be directly executed by the machine that is running the Java program.
Java programs can be easily moved from one computer to another, anywhere and anytime. Changes and upgrades in OS, processor and system resources will not force any changes in Java program. This is the reason why Java has become popular language on Internet which interconnects different kinds of systems worldwide. Java ensures portability in 2 ways. First, java compiler generates bytecode instructions that can be implemented on any machine. Second, the size of the primitive data types are machine-independent.
Java is a true object-oriented language. All program code and data reside within objects and classes. Java comes with an extensive set of classes, arranged in packages, that we can use in our programs by inheritance.
Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. It is designed as a garbage-collected language relieving the programmers virtually all memory management problems. Security becomes an important issue for a language that is used for programming on Internet. Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet.
Java is designed as a distributed language for creating applications on networks. It has the ability to share both data and programs. Java applications can open and access remote objects on Internet as easily as they can do in a local system. This enables multiple programmers at multiple remote locations to collaborate and work together on a single project.
Many features of C and C++ that are either redundant or sources of unreliable code are not part of Java. For example, Java does not use pointers, preprocessor header files, goto statement and many others. To make the language look familiar to the existing programmers, it was modeled on C and C++ languages.
Multithreaded means handling multiple tasks simultaneously. This means that we need not wait for the application to finish one task before beginning another. For example, we can listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer.
smoothly running interactive systems.
Java performance is impressive for an interpreted language, mainly due to use of intermediate bytecode. Java speed is comparable to the C/C++.
Java architecture is also designed to reduce overheads during runtime.
Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, and objects. Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program, depending on the response. Java supports functions written in other languages such as C and C++.
1. Ease of Development 2. Scalability and Performance 3. Monitoring and Manageability 4. Desktop Client 5. Core XML Support 6. Supplementary character support 7. JDBC RowSet
Java 2 Standard Edition (J2SE) 5.0 supports feature, such as Generics, Enhanced for Loop, Autoboxing or unboxing, Typesafe Enums, Varargs, static import and Annotation. These features reduce the work of the programmer by shifting the responsibility of creating reusable code to the compiler.
when compared to those made by the programmers.
J2SE 5.0 assures a significant in scalability and performance by improving the startup time and reducing the amount of memory used in Java 2 runtime environment. For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine (JVM) improves the startup time by loading the core classes from the jar files into a shared archive.
Java supports number of APIs, such as JVM Monitoring and Management API, Sun Management Platform Extension, Logging, Monitoring and Management Interface, and Java Management Extension (JMX) to monitor and manage Java applications. For example, JVM Monitoring and Management API is used to track the information at the application level and JVM level when deploying a large application.
J2SE 5.0 provides enhanced features to meet the requirements and challenges of the Java desktop users. It provides an improved Swing look and feel called Ocean. This feature is mainly used for developing graphics applications that require OpenGL hardware acceleration.
It adds powerful XML feature to the Java platform. Java contains some special packages for interface, to instantiate Simple API for XML(SAX) and Document Object Model (DOM) parsers to parse an XML document.
Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support. The supplementary characters are encoded with UTF-16 values to generate a different character called, surrogate codepoint.
Java is lot like C but the major difference is the Java is an Object-Oriented Language. Java does not include the C unique statement keywords sizeof and typedef. Java does not contain the data types struct and union. Java does not define the type modifiers keywords auto, extern, register, signed and unsigned. Java does not support an explicit pointer type. Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements.
It is the web browser from Sun Microsystems that enables the display of interactive content on the web, using the Java language. It is written entirely in Java. When the Java language was first developed and ported to the Internet, no browsers were available that could run Java applets. HotJava is currently available for SPARC/Solaris platform as well as Windows 95, Windows NT and Windows XP.
It is from Netscape Communication Corporation, is a general-purpose browser that can run Java applets. Available for Windows 95, NT, Solaris and Apple Macintosh, Netscape Navigator is one of the most widely used browser.
the number bytes downloaded.
It is another popular browser developed by Microsoft for Windows 95, NT and XP. Both Navigator and Explorer use tool bars, icons, menus and dialog boxes for easy navigation. Explorer uses a just-in-time (JIT) compiler which greatly increases the speed of execution.
Java is a general-purpose, object-oriented programming language. We can develop two types of Java programs:
and utilities.
class sampleone { public static void main(String args[]) { System.out.println(:Java is better than C++); } }
The first line declares a class, which is an object-oriented construct Java is a true object-oriented language so; everything must be placed inside a class.
Every class definition in Java begins with an opening brace “{“ and ends with a matching closing brace “}”.
The third line in the above program defines a method named main. Every Java application program must include the main() method. A Java program can have any number of classes but only one of them must include a main method. The keyword public is an access specifier that declares the main method as unprotected and therefore making it possible to all other classes. The keyword static, which declares this method as one that belongs to the entire class and not a part of any objects of the class. The main must be declared as static since the interpreter uses this method before any objects are created. The type modifier void states that the main method does not return any value.
String args[] declares a parameter named as args, which contains an array of objects of the class type String.
The only executable statement in the program is : System.out.println(:Java is better than C++); Since Java is a true object-oriented language, every method must be a part of an object. The println method is a member of the out object, which is a static data member of System class. The method println always appends a newline character to the end of the string.
A Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data member of the class. Methods may contain data type declarations and executable statements. A Java program may contain one or more sections as given below: Suggested Optional Optional Optional Optional Essential
The documentation section comprises a set of comment lines giving the name of the program. Comments explain why and what of classes and how of algorithms. Java uses a comment /*…../ known as documentation comment.
The first line allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. package student;
Before any class definitions it may be a number of import statements. This is similar to the #include statement in C. import student.test;
An interface is like a class but includes a group of method declarations. It is used only when we wish to implement multiple inheritance features in the program.
A Java program may contain multiple class definition. Classes are primary and essential elements of a Java program.
Every Java stand-alone program requires a main method as is starting point, this class is the essential part of a Java program. The main method crates objects of various classes and establishes communications between them.
A Java program is basically a collection of classes. A class is defined by a set of declaration statements and methods containing executable statements. Smallest individual units in a program are known as tokens. A Java program is a collection of tokens, comments and white spaces. It includes five types of tokens. They are:
Brackets [] Used to declare array types and for dereferencing array values Semicolon ; Used to separate statements Comma , Used to separate consecutive identifiers in a variable declaration. Also used to chain statements together inside a ‘for’ statement Period. Used to separate package names from sub-packages and classes, also used to separate a variable or method from a reference variable.
The statements in Java are like sentences in natural languages. A statement is an executable combination of tokens ending with a semicolon. Statements are executed in sequence in the order in which they appear. It is possible to control the flow of execution, if necessary, using special statements. Java Statements Statement Description Remarks Empty Statement These do nothing and are used during program development as a place holder Same as C and C++ Labeled Statement Any statement can begin with a label. Such labels must not be keywords, already declared local variables or previously used labels in this module. Labels in Java are used as the arguments of Jump statements. Identical to C and C++ except their use with jump statements Expression Statement Most statements are expression statements. Java has seven types of Expression statements: assignment, Pre-Increment, Pre-Decrement, Post-Increment, Post- Decrement, Method Call and Allocation Expression Same as C++ Selection Statement These select one of several control flows. There are three types of selection statements in Java: if, if-else, and switch Same as C and C++ Iteration Statement These specify how and when looping will take place. There are three types of iteration statements, while, do and for Same as C and C++ except for jumps and labels Jump statement Jump statements pass control to the beginning or end of the current block, or to a labeled statement. Such labels must be on an iteration statement. The four types of Jump statement are break, continue, return and throw C and C++ do not use labels with jump statements Synchronization Statement These are used for handling issues with multithreading Now available in C and C++ Guarding Statement Guarding statements are used for safe handling of code that may cause exceptions. These statements use the keywords try, catch and finally Same as in C++ except finally statement.
All language compilers translate source code into machine code for specific computer. Java compiler also does the same thing. Java compiler produces an intermediate code known as bytecode for a machine that does not exist. This machine is called the Java Virtual Machine and it exists only inside the computer memory. Process of compilation Source code Bytecode The virtual machine code is not machine specific. The machine specific code is generated by the Java interpreter by acting as an intermediary between the virtual machine. Process of converting bytecode into machine code Java Program Java Compiler Virtual Machine Bytecode Java Interpreter
Virtual Machine Real Machine UNIT II A programming language is designed to process certain kinds of data consisting numbers, characters and strings and to provide useful output known as information. The task of processing data is accomplished by executing a sequence of instructions constituting a program. These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules.
Constants refer to fixed values that do not change during the execution of program. Java supports several types of constants as shown below: JAVA CONSTANTS Machine code
‘\’ Backslash
A variable is an identifier that denotes a storage location used to store a data value. A variable may take different value at different times during the execution of the program. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Eg: average height total_height The rules for defining a variable names are:
Every variable in Java has a data type. Data types specify the size and type of values that can be stores. Java language is rich in its data types.
It can hold whole numbers. The size of the values that can be stored depends on the integer data type we choose, Java supports four types of integers. They are byte, short, int and long. Java does not support unsigned types and therefore all Java values are signed meaning they can be positive or negative.
It is used to hold numbers containing fractional parts such as 27.59 (known as floating point constants). There are two kinds of floating point storage. They are:
Numeric Integer Floating-point Non-numeric Character (^) Boolean Non-primitive Interface Classes lasses Arrays Integer Byte Short Int Long Floating Point Float (^) Double
The float type values are single-precision numbers while the double types represent double- precision numbers. Floating point numbers are treated as double-precision quantities. To force them to be in single precision mode, we must append f or F to the numbers. Eg: 1.23F
All mathematical functions such as sin, cos and sqrt return double type values. Floating point support a special value known as Not-a-Number(NaN). It is used to represent the result of operations such as division zero by zero, where an actual number is not produced.
To store character constants, Java provides a character data type called char. The character type assumes a size of 2 bytes but, it can hold only a single character.
It is used when we want to test a particular condition during the execution of the program. There are only two values that a Boolean type can take: true or false. It is denoted by the keyword Boolean and uses only one bit of storage. All comparison operators return Boolean type values. The words true or false cannot be used as identifiers.
Variables are the names of storage locations After designing suitable variable names, we must declare them to compiler. Declaration does three things:
A variable must be given a value after it has been declared but before it is used in an expression. This can be done in two ways:
A simple method of giving value to a variable is through the assignment statement. Syntax: variablename = value Eg: initialvalue = 0; We can also string assignment expression as x=y=z=0; It is also possible to assign a value to variable at the time of its declaration. Syntax: type variablename = value; Eg: int finalvalue=100; The process of giving initial value to variables is known as the initialization. The ones that are not initialized are automatically set to zero.
We may also give values interactively through the keyboard using the readLine() method.
One example pi=3. Another example is the total number of students whose mark-sheets are analyzed by a “test analysis program”. The number of students, say 50, may be used for calculating the class total, class average, standard deviation etc. We face two problems in the use of such programs. They are
We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of calculations or the number 50 to 100 to process the test result of another class. In both cases, we will have to search throughout the program and explicitly change the value of the constant wherever it has been used. If any value is left unchanged, the program may produce disastrous outputs.
When a numeric value appears in a program, its use is not always clear, especially when the same value means different things in different places. For example, the number 50 may mean the number of students at one place and the “pass marks” at another place of the same program. Symbolic constants Assignment of a symbolic name to such constants frees us from those problems. For example, we may use the name STRNGTH to denote the number of students and PASS_MARK to denote the pass marks required in a subject. Constant values are assigned to these names at the beginning of the program. Subsequent use of these variables in the program has the effect of causing their defined values to be automatically substituted at the appropriate points. Syntax: final type symbolic-name = value; Eg: f inal int STRNGTH = 100; final float PI = 3. Symbolic names take the same form as variable names. But, they are written in capitals to distinguish them from normal variable names. This is only a convention, not a rule. After declaration of symbolic constants, they should not be assigned any other value within the program by using an assignment statement. Symbolic constants are declared for types. This is not done in C and C++ where they are defined using the # define statement. They can not be declared inside a method. They should be used only as class data members in the beginning of the class.
parentheses. Syntax: type variable1 = (type) variable2; The process of converting one data type to another is called casting. Eg: int m=50; byte n = (byte)m; long count = (long) m; Four integer types can be cast to any other type except Boolean. Casting into a smaller type may result in a loss of data. The float and double can be cast to any other type except Boolean. Casting a floating point value to an integer will result in a loss of the fractional part.
byte short, char, int. long, float, double short int, long, float, double char int, long, float, double
int long, float, double long float, double float double
It is possible to assign a value of one type to a variable of a different type without a cast. Java does the conversion of the assigned value automatically. This is known as automatic type conversion. Automatic conversion is possible only if the destination type has enough precession to store the source value. byte b = 75; int a = b; The process of assigning a smaller type to a larger one is known as widening or promotion and that of assigning a larger type to a smaller one is known as narrowing. class A { public static void main (String args[]) { System.out.println(“Variables created”); char c=’x’; byte b=50; short s=1996; int i=12345; System.out.println(“C=”+c); Output System.out.println(“B=”+b); V ariables created System.out.println(“S=”+s); c=x System.out.println(“I=”+i); b= System.out.println(“Types converted”); s= short s1=(short)b; i= short s2=(short)i; //produces incorrect result Types converted System.out.println(“(short)b=”+s1); (short)b= System.out.println(“(short)i=”+s2); (short)i=- } }
Java supports two output methods that can be used to send the result to the screen.
a*b = 56 a/b = 3 (decimal part truncated) integer division a%b = 2 (remainder of integer division) For modulo division, the sign of the result is always the sign of the first operand. Eg: -14 % 3 = - 14 % -3 = 2
Floating Point Arithmetic involves only real operands of decimal or exponential notation. Unlike C and C++, % can be used with floating point data. The floating point modulus operator returns the floating point equivalent of an integer division. Eg: a = 20.5f b = 6.4f a + b = 26. a / b = 3. a % b = 1.
When one of the operands is real and the other is integer the expression is a mixed mode arithmetic expression. Eg: 15/10.0 = 1. 15/10 = 1
We often compare two quantities, and depending on their relation, take certain decision. For example compare the age of two persons, or the price of two items etc. The value of a relational expression is either one or zero. The arithmetic operators have a higher priority over relational operators. It is 1 if one is the specified relation is true and zero if it is false For eg: 10<20 is true 20<10 is false Relational Operators Operators Meaning < is less than <= is less than or equal to
is greater than = is greater than or equal to = = is equal to != is not equal to A simple relational expression contains only one relational operator and is of the form: ae-1 relational operator ae- ae-1 and ae-2 are arithmetic expressions, which may be variables or constants. Relational Expressions Expression Value 4.5<=10 TRUE 4.5<-10 FALSE -35>=0 FALSE 10<7+5 TRUE 4+3= =5+2 TRUE Relational expressions are used in decision making statements.
Logical Operators are used when we want to test more than one condition and make decisions. Here the operands can be constants, variables and expressions Logical Operators Operators Meaning && Logical AND || Logical OR ! Logical NOT For Example: a > b && x == 10 An expression of this kind which combines two or more relational expressions is termed as a logical expression or a compound relational expression.
Used to assign the result of an expression to a variable. = is the assignment operator.
In addition Java has a set of ‘short hand’ assignment operators of the form v op = exp ; Where v is a variable, exp is an expression and op is a Java binary operator The operator op= is known as shorthand assignment operator The assignment statement v op = exp ; x+= is equivalent to v = v op(exp); x = x + 1 Shorthand Assignment Operators Assignment Operator Shorthand Operator a = a + 1 a += 1 a = a - 1 a -= 1 a = a * (n+1) a *= n+ a = a / (n+1) a /= n+ a = a % b a %= b
The increment operator is ++ and decrement operator is – The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators ++m; or m++; equivalent to m = m + 1; or m += 1; // prefix --m; or m--; equivalent to m = m - 1; or m -= 1; // postfix A Prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. A postfix operator first assigns the value to the variable on the left and the increments the operand. class A Output { m= public static void main(String args[]) n= { ++m= int m = 10, n = 20; n++= System.out.println(“m=” +m); m= System.out.println(“n=” +n); n= System.out.println(“++m=” + ++m); System.out.println(“n++=” +n++); System.out.println(“m=” +m); System.out.println(“n=” +n); } }
The character pair ?: is used to check a condition and Select a Value depending on the Value of the condition. It is also called as ternary operator Variable = (condition)? Value 1 : Value 2; If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise Value2. Eg: big = (a>b)? a:b; This exp is equal to if (a>b) big = a; else big = b;
It is used to perform operations at binary level i. e. bitwise. These operators are used for testing the bits, or Shifting them right or left. These operators are not applicable to float or double. B itwise Operators Operators Meaning & bitwise AND ! bitwise OR ^ bitwise exclusive OR