Syllabus For Computer Programming II: Module 1: Introduction To Java
Syllabus For Computer Programming II: Module 1: Introduction To Java
Syllabus For Computer Programming II: Module 1: Introduction To Java
s as a platform, Simple programming Environment, Object Oriented, Platform independent, Safe, High Performance, Java is multithreaded, Dynamically linked, Java is garbage collected. Saving files on windows, Compiling and running .Increment and decrement operators. Print statements, Variables and data types, Comments and Command line arguments, objects, Static fields, Methods, Passing arguments to methods and returning values from methods Module 2: Primitive Data Types in JAVA Java operators, Literals, Identifiers, Keywords in Java, Addition, Multiplication, Division and Remainder operators in Java. Operator precedence in Java. Mixing data types in Java. Converting strings to numbers. Character data type in Java. The if, else, if-else statement in Java. The While loop, For loop, Do-while loop in Java. Booleans, Relational Operators and its precedence. Logical operators in Java. Break, Continue and Switch statement in Java. The ? : operator in Java Object Oriented Programming. Constructing objects with new, methods, Invoking methods. Implied this, member variable vs. local variables. Passing arguments to methods, returning multiple values from methods, constructors. Access protection and four levels of access protection Module 3: Array as a Data Structures in Java Declaring arrays, Creating Arrays, Initializing arrays. SystemArraycopy(). Multidimensional Arrays. Strings, toString() Methods, Vectors. Exceptions, try-catch, the finally keyword, Catch multiple exceptions. The throws keyword, Throwing exceptions Module 4: Inheritance Inheritance : the super class, Multilevel Inheritance, final and abstract keyword Interfaces, Implementing interfaces, Overriding Methods, Adding Methods, Subclasses, Polymorphism and static members Module 5: Multithreaded Programming Creating threads, extending the thread class, stopping and blocking a thread, Lifecycle Prof. Shalini Puri 1
of a thread, Using Thread methods, thread exceptions, thread priority, Synchronization. The JAVA Packages & Class library, wrapping your own Packages, Naming Packages, Documentation for the class library, Importing classes, Package Imports, Name conflicts when importing packages, the java.lang package, the hashCode() method of java.lang Object, java.lang.Math, java.util.Vector,java.lang.String, java.util. Random,java.util.hashtable,java.util.Date,and java.util.Calender Module 6 : HTML Attributes, URLs, Links, Applet, The Applet Element, Naming Applets, JAR archives, the OBJECT Element, Passing parameter to Applets. The Basic Applet Life cycle, init(), start( ),stop( ) and destroy( ). The coordinate System, Graphic objects, Loading images .Code and Documentation Bases, Drawing Images as Actual Size. Scaling images, Color, Fonts
List of programs for FE 2008-2009 for Computer Programming II: Sr.No 1 a) b) 2 3 4 5 6 7 a) b) 8 9 10 11 12 13 a) b) 14 15 Name of the program Area of triangle Printing the grade of a student Fibonacci series using while Armstrong Number using for G.C.D using do-while Search Elements of an array Printing Sum of diagonal elements in a two dimensional array Prime Number using function Reverse a number and sum of elements using Recursive function Implement class using Constructor Implement Array of Objects Implement String methods Exception Handling Multithreading Using pre-defined package Creating your own package Graphics in Applet Human face using Applet
INDEX 1. Introduction to Java.........................................................................................................6 1.1 Why is java popular for the Internet..........................................................................6 1.2 Features of Java:........................................................................................................6 1.3 How Java program runs.............................................................................................8 2. Object Orientation ........................................................................................................10 2.1 Features of Object Oriented Language:...................................................................10
3. Java Language Basics....................................................................................................12 3.1 Introduction:............................................................................................................12 3.2 Basic Building Blocks:............................................................................................12 4. Control Structures..........................................................................................................19 4.1 Simple If statement:.................................................................................................19 4.2 If-Else Statement:....................................................................................................19 4.3 Switch-Case Statement:...........................................................................................20 5. Loops.............................................................................................................................22 5.1 For Loop:.................................................................................................................22 5.2 While Loop:.............................................................................................................23 5.3 Do-While Loop:.......................................................................................................24 5.4 Break and Continue Statement:...............................................................................24 5.5 Exercise:...................................................................................................................26 6. Functions........................................................................................................................27 6.1 Methods in Java:......................................................................................................27 6.2 Recursive Functions:................................................................................................27 6.3 Exercise:...................................................................................................................28 7. Arrays............................................................................................................................31 7.1 Creating an Array:....................................................................................................31 7.2 Array Index Checking:.............................................................................................31 7.3 SystemArraycopy():.................................................................................................32 7.4 Multidimensional Arrays:........................................................................................33 7.5 Exercise:...................................................................................................................33 8. Introduction Classes:.....................................................................................................40 8.1 General form of a Class:..........................................................................................40 8.2 Declaring and Creating Objects:..............................................................................40 8.3 Accessing Members:................................................................................................41 8.4 Introducing Methods:...............................................................................................41 8.5 Constructors:............................................................................................................43 8.6 Array of Objects:......................................................................................................44 8.7 Static Variables and Static Methods:.......................................................................45 9. Wrapper Classes............................................................................................................47 9.1 Introduction:.............................................................................................................47 9.2 Class Integer:...........................................................................................................47 9.3 Class Float:...............................................................................................................47 9.4 Class Double:...........................................................................................................48 9.5 Class Boolean:.........................................................................................................48 9.6 Class Character:.......................................................................................................49 10. Strings.........................................................................................................................50 10.1 Declaring and Constructing a String:.....................................................................50 10.2 Methods of Strings:................................................................................................50 10.3 Sorting Strings:......................................................................................................51
10.4 Methods valueOf() and toString():.........................................................................52 10.5 Vector:...................................................................................................................52 11. Simple Input/Output...................................................................................................55 11.1 Reading Character fron Console Input:.................................................................55 11.2 Reading Strings:.....................................................................................................56 12. Inheritance...................................................................................................................58 12.1 Types of Inheritance:.............................................................................................58 12.2 Multilevel Inheritance:...........................................................................................62 12.3 Method Overriding:...............................................................................................65 12.4 Interface:................................................................................................................65 13. Packages.....................................................................................................................69 13.1 Defining and using your own Package:.................................................................69 13.2 Defining and using system Packages:....................................................................72 13.3 Access Specification in Java:.................................................................................77 14. Exception Handling....................................................................................................78 14.1 Why use Exception handling:...............................................................................78 14.2 Exceptions:.............................................................................................................79 15. Multithreading............................................................................................................85 15.1 What are Threads and why use them?...................................................................85 15.2 Creating and Running a Thread:............................................................................86 15.3 Life Cycle of a Thread:..........................................................................................90 15.4 Thread Priority:......................................................................................................92 15.5 Synchronization:....................................................................................................93 16. Graphics and Java Applets..........................................................................................95 16.1 Creation of Applet:................................................................................................95 16.2 Applet Life Cycle:..................................................................................................97 16.3 Using graphic methods in Applet:.........................................................................99 17. Solved University Question Papers: .........................................................................102 17.1 May-June 2008:...................................................................................................102 17.2 Dec-2008..............................................................................................................112
1. Introduction to Java
Java was developed at Sun Microsystems in 1991, by a team comprising James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan as its members. The language was initially called as Oak. It was later termed as Java. Java was launched on 23 May, 1995. The Java software was released as a development kit. The first two versions were named as JDK1.0 and JDK1.1. In 1998 while releasing the next version Sun Microsystems changed the name from Java Development Kit JDK) to Software Development Kit (SDK) and the version was referred as Java 2 SDK 1.2. Now we are using JDK 6.
1.2.3 Multithread Java is a programming language designed for the distributed environment of the internet and helps to write interactive programs where in multiple tasks can be performed simultaneously thus making it a robust programming language. Java is inherently multithreaded as there can be multiple executing threads in a single Java program. For example Java program can run three applets on the same page, provided that each applet gets equal time from the CPU. 1.2.4 Interpreted: Java is an interpreted language. When we write a program it is compiled into a class file. The interpreter executes this class file. However the interpreters 30 years ago were interpreting the statement in textual form. It was a very slow process. Java interprets byte code hence it is considerably fast. Java gets all the advantages of interpretation without suffering from major disadvantages.. 1.2.5 Architecture Neutral: Java is an Interpreter based language. With Java, the program need only be compiled once, and the code generated by the Java compiler can run on any platform (discussed in detail later). If you are writing software for the World Wide Web, being able to run the same program on many different systems is crucial to that program's success. Java is platform independent at both the source and the binary level. Java can be easily ported on any type of system and irrespective of the operating system being used. Java achieves this portability due to its feature of Implementation Independency. Platform independent and Portable: Platform independence is one of the most significant advantages that Java has over other programming languages, particularly for systems that need to work on many different platforms. Java is platform-independent at both the source and the binary level. Platform-independence is a programs capability of moving easily from one computer system to another. At the source level, Javas primitive data types have consistent sizes across all development platforms. Javas foundation class libraries make it easy to write code that can be moved from platform to platform without the need to rewrite it to work with that platform. Platform-independence doesnt stop at the source level, however. Java
binary files are also platform-independent and can run on multiple problems without the need to recompile the source. How does this work? Java binary files are actually in a form called byte codes. Byte codes are a set of instructions that looks a lot like some machine codes, but that is not specific to any one processor. Normally, when you compile a program written in C or in most other languages, the compiler translates your program into machine codes or processor instructions. Those instructions are specific to the processor your computer is runningso, for example, if you compile your code on a Pentium system, the resulting program will run only on other Pentium systems. If you want to use the same program on another system, you have to go back to your original source, get a compiler for that system, and recompile your code. 1.2.6 Distributed
Java is a distributed language as it can be used to create applications to communicate over the network. Java can communicate over the network because it supports TCP/IP (Transmission Control Protocol/Internet Protocol). The TCP/IP is a network communication protocol. 1.2.7 Dynamic During run time of a Java program, the relevant information is required that is used to verify and resolve access to objects. This concept of providing run time information is referred to as dynamically linking the code. This feature of Java adds strength to the applet environment in which all fragments of bytecode are dynamically updated on a running system.
Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java Hotspot virtual machine, perform additional steps at runtime to give your application a performance boost. This includes various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code Compilation in Java: Source Code Java Compiler Java ByteCode
Running a Java Program: Java ByteCode Computer Running Virtual Machine Java ByteCode
2. Object Orientation
2.1 Features of Object Oriented Language:
Encapsulation: The process of binding code and data together in the form of a capsule is Encapsulation. It is the mechanism that binds together code and data. It manipulates, and keeps it safe from outside interference and misuse. The data is not accessible to the outside world and only those functions that are wrapped in the class can access it. These functions provide the interface between the objects data and the program. The insulation of the data from the direct access by the program is called data hiding. In OOP, code and data are merged into an object so that the user of an object can never peek inside the box. This is defined as encapsulation (Object is a capsule encapsulating data and behavior). All communication to it is through messages (function calls which we use to communicate to the object). Messages define the interface to the object. Everything an object can do is represented by its message interface. Therefore, we need not know anything about what is in the object when we use it.
10
comprehend the complex earth. Inheritance The feature by which one class acquires the properties and functionalities of another class is Inheritance. Inheritance is the process by which one class acquires the properties and functionalities of another class. This is important because it supports the concept of hierarchical classification.. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it. Polymorphism: The feature that allows the same interface to be used for a general set of actions Polymorphism is a feature that allows one interface to be used for a general class of actions. An operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance. Ex: add(int a, int b) add(int a, float b, int c) add(int a, int b, float c, double d) Here different datatypes are being added using the same interface.
11
3.1
Introduction:
In our first program, we will find the area of a circle with radius 5. class area { public static void main(String args[]) { int r; r=5; System.out.println(3.14*r*r); } } If you run the program, you will get the following output: /*78.5*/ The structure of a very simple Java program can be explained as follows: 1. A program is written in a file named area.java 2. The file contains a class name as area by rule. 3. The class contains the main. It has to be declared with String arguments. 4. The method main contains declaration and program statements. 5. Java application begins execution at method main.
12
Integer Constant:
Integer can be expressed in three possible notations i.e. in octal, decimal and hexadecimal. We use integer constants in decimal form. These constants are either positive or negative. Plus sign is optional. In decimal: 23, -55, +2367. In Octal: 023, 055, 02367 In Hexdecimal : 0x23, 0x5B, 0XXFF23 Real Constant: The Real and floating point constants are written in either fixed point or scientific notation. Following are examples of valid real constants: In Fixed: 2.3, -5.54, 236.7 In Scientific: 0.2e3, -5E5, 2E67 Here for both mantissa and exponent sign is optional. Use of capital E is allowed in place of small e. Character Constant: If we enclose a single character in single quotes it forms simple character constants. Example: A,,B,* String Constant: A collection of characters is known as string. If we put characters in a pair of double quotes it forms a string constant. Example: Hello, World. 3.2.1 Variables: The variables are used to store values of constants. Any programming language allows us to change, manipulate the values stored in a variable. There are some rules that are to be followed while creating a variable name: 1. A variable name is a combination of 1 to 31 alphabets, digits or underscores. Do not write unnecessary long names as it adds up to your typing effort. 2. The first character in a variable name should be an alphabet. 3. No commas or blanks are allowed in the variable name. 4. No special symbols other than underscores are allowed in a variable name. 5. Try giving some relevant variable names.
13
Example: si_int,m_hra,pop_e_89 Declaration of Variable: Variables are declared with the help of a data type . a declaration int j tells the compiler that j is a variable of type int (integer). If we have more than one variable of type int then they are separated by commas. int i, j, k; Java or any other programming language aso allows us to assign values to the variables. int marks = 100; 3.2.2 Keywords: abstract const boolean continue break float byte default char else class extends 3.2.3 Operators:
Operators can perform operations on operands. Operands may be one, two or three. Operands are either variables or constants. The operands which take single operand are called unary operator. Those taking two are known as binary operators and one having three operands is called as ternary operator. Most of the operators are binary operators few are unary while there is only one ternary operator.
3.2.3.1 Arithmetic Operator:
class Operator { public static void main(String args[]) { int a=25,b=10; System.out.println("a+b =" +(a+b)); System.out.println("a-b =" +(a-b)); System.out.println("a*b =" +(a*b)); System.out.println("a/b =" +(a/b)); System.out.println("a%b =" +(a%b)); } } /*a+b =35 a-b =15 a*b =250 a/b =2 a%b =5*/ Prof. Shalini Puri 14
3.2.3.2
The ++ and - are Javas Increment and Decrement operators. The increment operator increases its operand by one. The decrement operator decreases the operand by one. Both are unary operators. For example this statement: x = x+1; can be rewritten like this by use of increment operator : x++;. Similarly, this statement: x = x-1; Is equivalent to x--; class InDec { public static void main(String args[]) { int a =5,b=5; System.out.println("a++ = "+(a++)); System.out.println("++b = "+(++b)); System.out.println("a-- = "+(a--)); System.out.println("--b = "+(--b)); } } /*a++ = 5 ++b = 6*/ a-- = 6 --b = 5*/
3.2.3.3 Relational Operator:
The relational operators determine the relationship that one operand has to the other. They determine equality and ordering. Operator Meaning == Equal to != Not Equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to class ROperator { public static void main(String args[]) { int a=25,b=10,c=67; Prof. Shalini Puri 15
System.out.println("a =" +(a)); System.out.println("b =" +(b)); System.out.println("c =" +(c)); System.out.println("a < b =" +(a < b)); System.out.println("a > b =" +(a > b)); System.out.println("a==c =" +(a==c)); System.out.println("a<=c =" +(a<=c)); System.out.println("a>=b =" +(a>=b)); System.out.println("a+b!=c =" +(a+b!=c)); System.out.println("a+b==c =" +(a+b==c)); } } /*a =25 b =10 c =67 a < b =false a > b =true a==c =false a<=c =true a>=b =true a+b!=c =true a+b==c =false*/
3.2.3.4 Logical Operator:
The logical operators shown here class Logical { public static void main(String args[]) { int a =5,b=5; System.out.println("a ="+a); System.out.println("b ="+b); System.out.println("a>b && a==b = "+(a>b && a==b)); System.out.println("a>b || a==b = "+(a>b || a==b)); } } /*a =5 b =5 a>b && a==b = false a>b || a==b = true*/
3.2.3.5 Bitwise Operator:
class bit { public static void main(String args[]) { int i=5; Prof. Shalini Puri 16
int a=2,b; int c=4,d=3; b= i | a; System.out.println(b+" "); d=(d & c); System.out.println(d+ " "); } } /*C:\Java\jdk1.5.0_17\bin>javac bit.java C:\Java\jdk1.5.0_17\bin>java bit 7 0*/
3.2.3.6 Shift Operators:
A shift operator performs bit manipulation by shifting the bits left or right. The bits of the first operand are shifted number of places as specified by the second operand. Java has two operators for this purpose. Operator Use Operation >> op1 >> op2 Shift bits of op1 right by distance op2 << op1 << op2 Shift bits of op1 left by distance op2 class shift { public static void main(String args[]) { int i,j; i= 6 << 2; j= 23 >> 2; System.out.println(i+" "); System.out.println(j+ " "); } } /*C:\Java\jdk1.5.0_17\bin>javac shift.java C:\Java\jdk1.5.0_17\bin>java shift 24 5*/
3.2.3.7 Conditional Operator:
Java includes a special ternary operator that can replace certain types of if .else statements. The character ? :is a ternary operator available in Java. The operator is used to construct conditional expression of the form: Expression ? Expression2 : Expression3 The operator ? : works as follows: Expression1 is evaluated first. If it is true then the
17
Expression2 is evaluated and becomes the value of the conditional expression. If Expression1 is false, Expression3 is evaluated and its value becomes the value of the conditional expression. Only one of the expressions either Expression2 or Expression3 is evaluated. For example consider the following statements: a = 30; b = 45; c = a >b ? a: b in this example c will be assigned the value of b. Program to demonstrate Ternary operator: class Cond { public static void main(String args[]) { int a =10,b=15,c=25,max; System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("c = "+c); max = a > b ? a : b; max = max > c ? max :c ; System.out.println("Maxm of 3 nos : "+max); } } /*a = 10 b = 15 c = 25 Maxm of 3 nos : 25*/
18
4. Control Structures
A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Javas program control
{ if(a>c) { System.out.println("a ="+a); } else { System.out.println("c="+c); } } else { System.out.println("b="+b); } } } /*Largest value is : b=712*/
} The expression must be type byte, short, int or char each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal. Duplicate case values are not allowed. The switch statement works like this: the value of the expression is compared with each of the literal values in the case statements. If a match is found the code sequence following that case statement is executed. If none of the constants matches the value of expression then the default statement is executed. However the default statement is optional. If no case matches and no default is present, then no further action is taken.The break statement is used in switch to terminate a statement sequence. When a break
20
statement is encountered execution branches to the first line of code that follows the entire switch statement. This has effect of jumping out of the switch. The switch statement is used for designing menu driven interactive programs. class Switch { public static void main(String args[]) { int x=Integer.parseInt(args[0]); int y= Integer.parseInt(args[1]); String s =args[2]; char op =s.charAt(0); switch(op) { case '+': System.out.println(x +"+" + y +"="+ (x+y)); break; case '-': System.out.println(x +"-" + y +"="+ (x-y)); case '/': System.out.println(x +"/" + y +"="+ (x/y)); break; case '%': System.out.println(x +"%" + y +"="+ (x%y)); break; } } } /*C:\ava\jdk1.5.0_04\bin>java Switch 23 45 +23+45=68 C:\Java\jdk1.5.0_04\bin>java Switch 23 45 23-45=-22 C:\Java\jdk1.5.0_04\bin>java Switch 23 45 / 23/45=0 C:\Java\jdk1.5.0_04\bin>java Switch 23 45 % 23%45=23*/
21
5. Loops
Javas iteration statements are for, while, do-while. These statements create what we commonly call loops.
22
23
In Java the statement has three uses: 1. It terminates a statement a sequence in a switch statement. 2. It can be used to exit a loop. class Break { public static void main(String args[]) { for(int i=1;i<100;i++) { if(i==10) Prof. Shalini Puri 24
break; System.out.print(i +" "); } } } /*C:\Java\jdk1.5.0_04\bin>javac Break.java C:\Java\jdk1.5.0_04\bin>java Break 123456789 */ 5.4.2 Continue Statement: The continue statement is used to force an early iteration of a loop. This means we
may continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. The continue statement performs such an action. In the while and do-while loops a continue statement cause control to be transferred directly to the conditional expression that controls the loop. In a for loop control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops any intermediate code is bypassed. As with the break statement continue may specify a label to describe enclosing loop to continue class Continue { public static void main(String args[]) { for(int i=0;i<10;i++) { System.out.print(i +" "); if(i%2==0) continue; System.out.println(""); } } } /*C:\Java\jdk1.5.0_04\bin>javac Continue.java C:\Java\jdk1.5.0_04\bin>java Continue 01 23 45 67 8 9*/
25
5.5 Exercise:
1. 2. 3. 4. 5. 6. 7. 8. Write a program display table for 15. Write a program for calculating the squares and cubes of the first 10 numbers. Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7. Write a program to find out first 10 prime numbers. Write a program to find out whether a number is an Armstrong number or not. Write a program to find out whether a number is a palindrome or not. Write a program to find out the factorial of first 10 numbers. Write a program to calculate the Permutation and Combination. Pr = (n!/r!) Cr =(n!/r!(n-r)! 9. 10. 11. 12. 13. 14. Write a program to implement x raise to n. Write a program to find out sine series Write a program to find out cosine series Generate Pascals triangle. Find the sum of sequence 1 + 1/3 -1/4+ 1/5. Find the sum of sequence 1 + 1/1! + ! + 1/3!
26
6. Functions
Functions are small pieces of code doing a particular task. Functions are called methods in Java.
27
class Recursive { public static void main(String args[]) { int n=5; int f; f=fact(n); System.out.println("Factorial is = "+ f); } public static int fact(int n) { if(n==0) return(1); else return(n*fact(n-1)); } } /*C:\Java\jdk1.5.0_17\bin>javac Recursive.java C:\Java\jdk1.5.0_17\bin>java Recursive Factorial is = 120*/
6.3 Exercise:
1. Write a program to print the Fibonacci series using recursive function. class Fibonacci { public static void main(String args[]) { int n=8; System.out.print("The fibonacci series is :"); for(int i=0;i<n;i++) { System.out.print(fib(i)+" ");; } } public static int fib(int n) { if(n==0 || n==1) return(1); else return(fib(n-1)+fib(n-2)); } } C:\Java\jdk1.5.0_17\bin>javac Fibonacci.java C:\Java\jdk1.5.0_17\bin>java Fibonacci The fibonacci series is :1 1 2 3 5 8 13 21
28
2. Write a program to print the Reverse and sum of integers using recursive function. class Parameter { public static void main(String args[]) { int n=1234,s=0; System.out.print("The reverse of number is :"); s=reverse(n,0); System.out.println(); System.out.println("Sum of Digits is = "+ s); } public static int reverse(int x,int y) { int d; if(x==0) return(y); else { d=x%10; System.out.print(d+" "); y=y+d; } return(reverse(x/10,y)); } } /*C:\Java\jdk1.5.0_17\bin>javac Parameter.java C:\Java\jdk1.5.0_17\bin>java Parameter The reverse of number is :4 3 2 1 Sum of Digits is = 10*/ 3. Write a program to print G.C.D of two number using recursive functions class GCD { static int gcd(int a,int b) { int r=a%b; if(r==0) return(b); else return(gcd(b,r)); } public static void main(String args[]) { int a=27,b=81; Prof. Shalini Puri 29
30
7. Arrays
An array is a group of contiguous or related data items that share a common name. For instance we can define an array name salary to represent a set of salaries of a group of employees. A particular value is indicated by writing a number called index number or subscript in brackets after the array name. For example, salary[10] represents the salary of the 10th employee. While the complete set of values is referred to as an array, the individual values are called elements. Arrays can be of any variable type. The ability to use a single name to represent a collection of items and to refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with the subscript as the control variable can be used to read the entire array, perform calculations and print out the results.
31
int n=num.length; System.out.println("The List is :"); for(int i=0;i<n;i++) { System.out.println(num[i]+" "); sum+=num[i]; } System.out.println("Sum ="+(sum)); } } /*The List is : 55 40 80 65 71 Sum =311*/
7.3 SystemArraycopy():
If we want to make a true copy of an array we must make a new array of the same length as the original and copy overall values: double [] prices = new double[data.length]; for(int i=0;i<data.length;i++) prices[i] = data[i]; Instead of the for loop you can also use the static System.arrayCopy method. The method can be used to copy any portion of an array into another array. System.arrayCopy (from,fromStart,to,toStart,count); To copy the entire data array into the prices array we say: System.arrayCopy(data,0,prices,0,data.length); class ArrayCopy { public static void main(String[] args) { int x[] = {11,22,33,44,55}; int y[] = new int[5]; System.arraycopy(x,0,y,0,5); System.out.println("Array y after copying is :"); for(int i=0;i<5;i++) {System.out.print(" " + y[i]); } } } /*C:\Java\jdk1.6.0_05\bin>javac ArrayCopy.java C:\Java\jdk1.6.0_05\bin>java ArrayCopy Array y after copying is : 11 22 33 44 55 */
32
The table contains a total of 12 values three in each line. We can think of this table as a matrix consisting of four rows and three columns. Each row represent the value of sales by a particular salesgirl and each column represents the value of sales of a particular item. Java allows us to define such tables of items using two dimensional arrays. The table discussed above can be represented in Java as v[4][3]. For creating two dimensional arrays we must follow the same steps as a single dimensional array. int myArray [ ] [ ] = new int [3][4];
7.5 Exercise:
7.5.1 Linear Search: class search { public static void main(String args[]) { int x[]= {23,55,14,18,67}; int r, n = 5,i; r=Integer.parseInt(args[0]); System.out.print("List of elements : "); for(i=0;i<n;i++) { System.out.print(x[i]+ " "); } System.out.println(); for(i=0;i<n;i++) { if(r==x[i]) { System.out.println("Element " +r+" found at " + i +" position"); break; } Prof. Shalini Puri 33
} if(i==n) System.out.println("Element not found"); } } /*C:\Java\jdk1.5.0_17\bin>javac search.java C:\Java\jdk1.5.0_17\bin>java search 18 List of elements : 23 55 14 18 67 Element 18 found at 3 position C:\Java\jdk1.5.0_17\bin>java search 17 List of elements : 23 55 14 18 67 Element not found*/ 7.5.2 Sorting an Array: class Sort { public static void main(String args[]) { int num[]={55,40,80,65,71},sum=0; int n=num.length; System.out.println("The List is :"); for(int i=0;i<n;i++) { System.out.println(num[i]+" "); } for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { if(num[i]>num[j]) { int temp = num[i]; num[i]=num[j]; num[j]=temp; } } } System.out.println("The Sorted List is :"); for(int i=0;i<n;i++) { System.out.println(num[i]+" "); } } } /*The List is : 55 40 80 65 71
34
The Sorted List is : 40 55 65 71 80*/ 7.5.3 Checking for duplicate elements: class search { public static void main(String args[]) { int x[]= {23,55,18,18,67}; int r, n = 5,i,c=0; r=Integer.parseInt(args[0]); System.out.print("List of elements : "); for(i=0;i<n;i++) { System.out.print(x[i]+ " "); } System.out.println(); for(i=0;i<n;i++) { if(r==x[i]) { System.out.println("Element " +r+" found at " + i +" position"); c++; } } if(c==0) System.out.println("Element not found"); else System.out.println("Element found "+ c +" times"); } } /*C:\Java\jdk1.5.0_17\bin>javac search.java C:\Java\jdk1.5.0_17\bin>java search 18 List of elements : 23 55 18 18 67 Element 18 found at 2 position Element 18 found at 3 position Element found 2 times C:\Java\jdk1.5.0_17\bin>java search 17 List of elements : 23 55 18 18 67 Element not found 7.5.4 Matrix Addition: class matadd { public static void main(String args[]) { Prof. Shalini Puri 35
int ROWS=4,COLS=4; int x[][]=new int[ROWS][COLS]; int y[][]=new int[ROWS][COLS]; int z[][]=new int[ROWS][COLS]; for(int i=0,k=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { x[i][j]=k+1; k++; } } for(int i=0,k=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { y[i][j]=k+1; k++; } } for(int i=0,k=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { z[i][j]=(x[i][j]+y[i][j]); } } System.out.println("The X array is :"); for(int i=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { System.out.print(" "+x[i][j]); } System.out.println(); } System.out.println("The Y array is :"); for(int i=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { System.out.print(" "+y[i][j]); } System.out.println(); } System.out.println("The Z array is :");
36
for(int i=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { System.out.print(" "+z[i][j]); } System.out.println(); } } } /*C:\Java\jdk1.5.0_17\bin>javac matadd.java C:\Java\jdk1.5.0_17\bin>java matadd The X array is : 1234 5678 9 10 11 12 13 14 15 16 The Y array is : 1234 5678 9 10 11 12 13 14 15 16 The Z array is : 2468 10 12 14 16 18 20 22 24 26 28 30 32*/ 7.5.5 Matrix Multiplication: class Matrix { public static void main(String args[]) { int ROWS=4,COLS=4; int x[][]=new int[ROWS][COLS]; int y[][]=new int[ROWS][COLS]; int z[][]=new int[ROWS][COLS]; for(int i=0,k=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { x[i][j]=k+1; k++; } } for(int i=0,k=0;i<ROWS;i++)
37
{ for(int j=0;j<COLS;j++) { y[i][j]=k+1; k++; } } for(int i=0,k=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { z[i][j]=0; for(k=0;k<ROWS;k++) { z[i][j]+=(x[i][k]*y[k][j]); } } } System.out.println("The X array is :"); for(int i=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { System.out.print(" "+x[i][j]); } System.out.println(); } System.out.println("The Y array is :"); for(int i=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { System.out.print(" "+y[i][j]); } System.out.println(); } System.out.println("The Z array is :"); for(int i=0;i<ROWS;i++) { for(int j=0;j<COLS;j++) { System.out.print(" "+z[i][j]); } System.out.println(); } }
38
} /*The X array is : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 The Y array is : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 The Z array is : 90 100 110 120 202 228 254 280 314 356 398 440 426 484 542 600*/
39
8. Introduction Classes:
Class can be considered as a user defined data type. It is a template for the object to be created. It holds some data. Let us take an example of time. It consists of hours, minutes and seconds. To store these quantities, we need three different fields (variables). But together they constitute a single object.
40
hour=a; minute=b; second=c; } void putdata() { System.out.println("Hour = " +hour); System.out.println("Minute = " +minute); System.out.println("Second = " +second); total=hour*60*60+minute*60+second; System.out.println("Total Seconds = "+total); } } class TDetail { public static void main(String args[]) { Time T =new Time(); T.getdata(2,25,56); T.putdata(); } } /*C:\Java\jdk1.5.0_17\bin>javac TDetail.java C:\Java\jdk1.5.0_17\bin>java TDetail Hour = 2 Minute = 25 Second = 56 Total Seconds = 8756*/
void convert(int n) { hour=n/60; minute=n%60; } void display() { System.out.println(hour + " " +minute); } } class TDetails { public static void main(String args[]) { Time T =new Time(); T.convert(384); T.display(); } } /*C:\Java\jdk1.5.0_17\bin>javac TDetails.java C:\Java\jdk1.5.0_17\bin>java TDetails 6 24*/ 8.4.2 Methods with parameters as Objects: class Time { int hour,minute,second; void getdata(int h,int m,int s) { hour=h; minute=m; second=s; } Time convert(Time A) { Time temp=new Time(); temp.second=second+A.second; temp.minute=temp.second/60; temp.second=temp.second%60; temp.minute+=minute+A.minute; temp.hour=temp.minute/60; temp.minute=temp.minute%60; temp.hour+=hour+A.hour; return(temp); } void display()
42
{ System.out.println(hour + " " +minute+ " "+second); } } class TMDetail { public static void main(String args[]) { Time T1 =new Time(); Time T2=new Time(); T1.getdata(3,54,45); T1.display(); T2.getdata(2,44,23); T2.display(); Time T3=new Time(); T3=T1.convert(T2); T3.display(); } } /*C:\Java\jdk1.5.0_17\bin>javac TMDetail.java C:\Java\jdk1.5.0_17\bin>java TMDetail 3 54 45 2 44 23 6 39 8*/
8.5 Constructors:
All objects that are created must be given initial values. There are two ways of initializing the variables of objects. The first approach uses the dot operator to access the instance variables and then assign values to them individually. It can be tedious approach to initialize all the variables of all the objects. The second approach takes the help of a method like getdata to initialize each object individually class Rectangle { int length,width; Rectangle(int x,int y) { length=x; width=y; } int rectarea() { return(length*width); }
43
} class RectangleArea { public static void main(String args[]) { Rectangle Room=new Rectangle(10,20); System.out.println("Area ="+Room.rectarea()); } } /*Area =200*/
x=Integer.parseInt(obj.readLine()); System.out.println("Enter Name :"); str=obj.readLine(); System.out.println("Enter Salary :"); f=Float.parseFloat(obj.readLine()); a[i].get(x,str,f); } for(i=0;i<2;i++) { a[i].put(); } } } /*E:\\Java\jdk1.5.0_16\bin>javac EmpDetail.java E:\Java\jdk1.5.0_16\bin>java EmpDetail Enter Rollno :1 Enter Name :shalini Enter Salary :5000 Enter Rollno :2 Enter Name :ajay Enter Salary :6000 1 shalini 5000.0 2 ajay 6000.0*/
45
class. One of the most common examples is to have a variable that could keep a count of how many objects of a class have been created. Java creates only one copy for a static variable which can be used even if the class is actually instantiated. Like static variables static methods can be called without using the objects. They are also available for use by other classes, methods that are of general utility but do not directly affect an instance of that class are usually declared as class methods. The static methods are called using class names. No objects have been created for use. Static methods have several instructions: 1. They can call only call other static methods. 2. They can access only static data. 3. They cannot refer to this or super in any way. class MathOperation { static int mul(int x,int y) { return(x*y); } static int divide(int x,int y) { return(x/y); } } class MathApplication { public static void main(String args[]) { int a = MathOperation.mul(3,5); int b = MathOperation.divide(a,2); System.out.println("b ="+b); } } /*C:\Java\jdk1.6.0_05\bin>javac MathApplication.java C:\Java\jdk1.6.0_05\bin>java MathApplication b =7*/
46
9. Wrapper Classes
When we give gifts, we wrap them nicely in a box. The gift may be a doll or a toy car or something else. The box and the glossy paper round it make it attractive. We have worked with simple data types. Now java will wrap them and make it attractive. For this Java provides an interesting concept of wrapper classes.
9.1 Introduction:
We have studied the basic data type float. It holds the floating-point number. Now Java provides a class Float. As identifiers are case sensitive float and Float are different. The new class Float is for storing floating-point. Similarly an int is wrapped in a class Integer. It also has methods that work within this class. The other wrapper classes are Byte, Short, Integer, Long and Double.
Float f3 = new Float("2.7"); System.out.println("f1 ="+f1); System.out.println("f2 ="+f2); System.out.println("f3 ="+f3); System.out.println("Max Value = "+Float.MAX_VALUE); System.out.println("Min Value = "+Float.MIN_VALUE); } } /*C:\Java\jdk1.5.0_17\bin>javac float1.java C:\Java\jdk1.5.0_17\bin>java float1 f1 =2.5 f2 =2.6 f3 =2.7 Max Value = 3.4028235E38 Min Value = 1.4E-45*/
49
10. Strings
Strings are very important part of the programming language as they are used to process long textual/symbolic information. For example when we visit a bank to open an account then we are asked for information such as name, address. The information we provide is in the form of ordered sequence of characters and symbols. The ordered sequence of characters and symbols is known as String.
class DString { public static void main(String args[]) { String Name =new String("Shalini"); Prof. Shalini Puri 50
System.out.println("Name = " +Name); int len=Name.length(); System.out.println("Length = "+len); String N1=new String(); N1=Name.toLowerCase(); System.out.println("Lower Case of Name = " +N1); String N2=new String(); N2=Name.toUpperCase(); System.out.println("Upper Case of Name = " +N2); String N3=new String(); N3=Name.replace('i','b'); System.out.println("Upper Case of Name = " +N3); System.out.println("Name equals N1 = " +Name.equals(N1)); System.out.println("Name equals N1 = " +Name.equalsIgnoreCase(N1)); System.out.println("Name compares N1 = " +Name.compareTo(N1)); System.out.println("N1 compares Name = " +N1.compareTo(Name)); System.out.println("Concatenate Name with string = " +Name.concat("Puri")); System.out.println("Substring of Name = " +Name.substring(3)); System.out.println("Substring of Name = " +Name.substring(2,5)); System.out.println("Index of i in Name = " +Name.indexOf('i')); } } /*Name = Shalini Length = 7 Lower Case of Name = shalini Upper Case of Name = SHALINI Upper Case of Name = Shalbnb Name equals N1 = false Name equals N1 = true Name compares N1 = -32 N1 compares Name = 32 Concatenate Name with string = ShaliniPuri Substring of Name = lini Substring of Name = ali Index of i in Name = 4*/
System.out.println("Names before sorting :"); for(i=0;i<n;i++) System.out.print(name[i]+ " "); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { int x=name[i].compareTo(name[j]); if(x>0) { temp=name[i]; name[i]=name[j]; name[j]=temp; } } } System.out.println(); System.out.println("Names after sorting :"); for(i=0;i<n;i++) System.out.print(name[i]+" "); } } /*C:\Program Files\Java\jdk1.5.0_17\bin>javac Sort.java C:\Program Files\Java\jdk1.5.0_17\bin>java Sort Names before sorting : raj ajay amar sita nitin Names after sorting : ajay amar nitin raj sita*/
10.5 Vector:
Java provides a feature of a vector class contained in the java.util package. This class can be used to create generic dynamic array known as vector that can be used to hold objects of any type & any number. The objects do not have to be homogeneous. Arrays can be easily implemented as vectors. Vectors can be created like arrays as follows: Vector intVect = new Vector( ); Vector list = new Vector(3). // Declaring without size. // Declaring with size.
52
Note that a vector can be declared without specifying any size explicitly. A vector can accommodate an unknown number of items. Even when a size is specified it can be overlooked and a different number of items may be put into the vector. But if we compare it with an array the size of the array has to be specified. Vectors possess a number of advantages over arrays. It is convenient to use vectors to store objects. A vector can be used to store a list of objects that may vary in size. We can add and remove objects from the list as and when required. Task Performed Add the item specified to the list at the end Gives the name of the 10th object Gives the number of objects present Removes the specified item from the list Removes the item stored in the nth position of the list Removes all elements in the list. Copies all items from the list to array Inserts the item at nth position
Important vector methods: Method call list.addElement(item) list.elementAt(10) list.size() list.removeElement(item) list.removeElementAt(n) list.removeAllElements() list.copyInto(array() List.insertElementAt(item,n)
The above program illustrates the use of arrays, strings and vectors. This program converts a string vector into an array of strings and displays the strings. import java.util.*; class LanguageVector { public static void main(String[] args) { Vector list =new Vector( ); int length = args.length; for(int i=0;i<length;i++) { list.addElement(args[i]); } list.insertElementAt("COBOL",2); int size =list.size( ); String listArray[] = new String[size]; list.copyInto(listArray); System.out.println("List of languages :"); for(int i=0;i<length;i++) { System.out.println(listArray[i]); Prof. Shalini Puri 53
} } } /*C:Java\jdk1.6.0_05\bin>javac LanguageVector.java C:\Java\jdk1.6.0_05\bin>java LanguageVector Ada Basic C++ FORTRAN Java List of languages : Ada Basic COBOL C++ FORTRAN Java C:\Java\jdk1.6.0_05\bin>*/
54
55
data is being read from the standard input device, the System.in should be wrapped in the DataInputStream object. This wrapping of the DataInputStream object allows users to obtain the byte stream attached with the console. The following code is used to wrap the System.in in the DataInputStream. And further a read () method is used to read the data. import java.io.*; class ReadChar { public static void main(String args[]) { DataInputStream obj=new DataInputStream(System.in); char ch =' '; try { System.out.println("Enter Q to exit "); while(ch!='Q') { ch=(char)obj.read(); System.out.println(ch); } } catch(Exception e) { System.out.println(e); } } } /* C:\Program Files\Java\jdk1.5.0_17\bin>javac ReadChar.java C:\Program Files\Java\jdk1.5.0_17\bin>java ReadChar Enter Q to exit ShaliniQ ShaliniQ*/
int i; for(i=0;i<10;i++) { str[i]=obj.readLine(); if(str[i].equals("Q")) break; } System.out.println("Text entered by is :"); for(i=0;i<10;i++) { if(str[i].equals("Q")) break; System.out.println(str[i]); } } } /*C:\Program Files\Java\jdk1.5.0_17\bin>javac ReadChar.java C:\Program Files\Java\jdk1.5.0_17\bin>java ReadChar Enter some text, Q to quit Welcome to the World of Java Q Text entered by is : Welcome to the World of Java*/
57
12. Inheritance
In object oriented programming the term Inheritance refers to the fact that one class can inherit part or all of its structure and behavior from another class. The class that does the inheriting is said to be a subclass of the class from which it inherits. If class B is a subclass of A we also say that class A is a super class of class B. A subclass can add to the structure and behavior that it inherits .It can also modify inherited behavior. The relationship between subclass and super class is shown by the below diagram. Class A (superclass)
Class B (subclass) Java uses the extends keyword to set the relationship between a child class and a parent class. For example to create a class named B as a subclass of class named A we would write: Class B extends A { .. }
A B
A program that illustrates Single level Inheritance: class Room { int length,breadth; Room(int l,int b) Prof. Shalini Puri 58
{ length=l; breadth=b; } int area() { return(length*breadth); } } class BedRoom extends Room { int height; BedRoom(int x,int y,int z) { super(x,y); height=z; } int volume() { return(length*breadth*height); } } class InherTest { public static void main(String args[]) { BedRoom Room1=new BedRoom(10,20,30); int area1=Room1.area(); int volume1=Room1.volume(); System.out.println("Area = "+area1); System.out.println("Volume = "+volume1); } } /*Area = 200 Volume = 6000*/ 2. subclasses) The features of one class may be inherited by more than one class this process is known as Hierarchical Inheritance. Hierarchical Inheritance : ( one super class and many
A B
Prof. Shalini Puri
D
59
The below program illustrates Hierarchical Inheritance: class Shape { protected double bs,ht,area; void getdata(double b,double h) { bs=b; ht=h; } } class Triangle extends Shape { void display() { area=0.5*bs*ht; System.out.println("Area of triangle is "+area); } } class Rectangle extends Shape { void display() { area=bs*ht; System.out.println("Area of triangle is "+area); } } class HITest { public static void main(String args[]) { Triangle T = new Triangle(); Rectangle R = new Rectangle(); T.getdata(3.5,7.5); T.display(); R.getdata(4,4); R.display(); } } /*Area of triangle is 13.125 Area of triangle is 16.0*/
60
12.1.1 Super: A sub class can call a constructor method defined by its super class by the use of the following form of super: super(parameter list); Here parameter list specifies any parameters needed by the constructor in the super class. super( ) must always be the first statement executed inside a sub classs constructor. To see how super is used consider the following program:
class Vehicle { private String Make; private double Milage; Vehicle(String m,double d) { Make=m; Milage=d; } void display() { System.out.println("Name of the company :"+Make); System.out.println("Milage of the Vehicle :"+Milage); } } class TwoWheeler extends Vehicle { private char clutch; TwoWheeler(String m,double d,char c) { super(m,d); clutch=c; } void display() { super.display(); System.out.println("Clutch present :"+clutch); } Prof. Shalini Puri 61
} class FourWheeler extends Vehicle { private char Ac; FourWheeler(String m,double d,char c) { super(m,d); Ac=c; } void display() { super.display(); System.out.println("AC present :"+Ac); } } class transport { public static void main(String args[]) { TwoWheeler T =new TwoWheeler("Hero Honda",70,'y'); FourWheeler F =new FourWheeler("Maruti",17,'y'); T.display(); F.display(); } } /*Name of the company :Hero Honda Milage of the Vehicle :70.0 Clutch present :y Name of the company :Maruti Milage of the Vehicle :17.0 AC present :y*/
A B C
Prof. Shalini Puri 62
The program below illustrates Multilevel Inheritance: class Student { int RollNo; String Name; Student(int a,String n) { RollNo=a; Name=n; } void display() { System.out.println("Roll No = "+RollNo); System.out.println("Name = "+Name); } } class Test extends Student { float m1,m2; Test(int a,String m,float x,float y) { super(a,m); m1=x; m2=y; } void show() { System.out.println("Marks 1 = "+m1); System.out.println("Marks 2 = "+m2); } } class Result extends Test { float total; Result(int a,String m,float x,float y) { super(a,m,x,y); } void showRes() { System.out.println("Result = "+(m1+m2)); } } Prof. Shalini Puri 63
class MulTest { public static void main(String args[]) { Result R = new Result(1,"Shalini",50,67); R.display(); R.show(); R.showRes(); } } /*Roll No = 1 Name = Shalini Marks 1 = 50.0 Marks 2 = 67.0 Result = 117.0*/ 12.2.1 Protected: The access specifier works as private for the outside world but works as public for derived classes. Let us take the following example: class Student { protected int RollNo; protected String Name; Student(int a,String n) { RollNo=a; Name=n; } } class Test extends Student { protected float m1,m2; Test(int a,String m,float x,float y) { super(a,m); m1=x; m2=y; } void show() { System.out.println("Roll No = "+RollNo); System.out.println("Name = "+Name); } } class Result extends Test
64
{ float total; Result(int a,String m,float x,float y) { super(a,m,x,y); } void showRes() { System.out.println("Marks 1 = "+m1); System.out.println("Marks 2 = "+m2); System.out.println("Result = "+(m1+m2)); } } class MulTest { public static void main(String args[]) { Result R = new Result(1,"Shalini",50,67); R.show(); R.showRes(); } } /*C:\Program Files\Java\jdk1.5.0_17\bin>javac MulTest.java C:\Program Files\Java\jdk1.5.0_17\bin>java MulTest Roll No = 1 Name = Shalini Marks 1 = 50.0 Marks 2 = 67.0 Result = 117.0*/
12.4 Interface:
The object oriented programming languages such as C++ allows a class to extend two or more super classes. This is called multiple inheritance. But Multiple Inheritance is not allowed in Java so it provides an alternate approach as interfaces to support it. Interface is basically a kind of class. The difference is that interfaces do not specify any code to implement these methods and data fields contain only constants. Therefore it is Prof. Shalini Puri 65
the responsibility of the class that implements an interface to define the code for implementation of these methods. The syntax for defining an interface is very similar to that for defining a class. The general form of an interface definition is: interface InterfaceName { Variable declaration; Method declaration; } Here interface is the keyword and InterfaceName is any valid Java variable (just like the class names). Variables are declared as follows: interface Area { float pi =3.142F; float compute (float x, float y); void show( ); } 12.4.1 Implementing Interfaces: Interfaces are used as super classes whose properties are inherited interface Area { final float pi =3.14F; float compute(float x,float y); } class Rectangle implements Area { public float compute (float x,float y) { return(x*y); } } class Circle implements Area { public float compute (float x,float y) { return(pi*x*x); } } class InterfaceTest { public static void main(String[] args) { Rectangle R =new Rectangle();
66
Circle C =new Circle(); System.out.println("Area of Rectangle :"+ R.compute(10,20)); System.out.println("Area of Circle :"+ C.compute(10,0)); } } /*C:\Java\jdk1.6.0_05\bin>javac InterfaceTest.java C:\Java\jdk1.6.0_05\bin>java InterfaceTest Area of Rectangle :200.0 Area of Circle :314.0*/ 12.4.2 Implementing Hybrid Inheritance: class Student { int RollNo; void getNumber(int n) { RollNo=n; } void putNumber() { System.out.println("Roll No :"+RollNo); } } class Test extends Student { float part1,part2; void getMarks(float m1,float m2) { part1=m1; part2=m2; } void putMarks() { System.out.println("Marks obtained :"); System.out.println("Part 1 ="+part1); System.out.println("Part 2 ="+part2); } } interface Sports { float sportWt =6.0F; void putWt(); } class Result extends Test implements Sports { float total;
67
public void putWt() { System.out.println("Sporst Wt ="+sportWt); } void display() { total=part1+part2+sportWt; putNumber(); putMarks(); System.out.println("Total Score ="+total); } } class Hybrid { public static void main(String[] args) { Result student1 = new Result(); student1.getNumber(234); student1.getMarks(27.5F,33.05F); student1.display(); } } /*C:\Java\jdk1.6.0_05\bin>javac Hybrid.java C:\Java\jdk1.6.0_05\bin>java Hybrid Roll No :234 Marks obtained : Part 1 =27.5 Part 2 =33.05 Total Score =66.55*/
68
13. Packages
The main feature of OOP is its ability to reuse the code already created. One way of achieving this is by extending classes and implementing the interfaces but it creates a limitation of reusing the classes within a program. What if we need to reuse classes from other programs without physically copying them into the program under development? This can be accomplished in Java by using what is known as packages a concept similar to class libraries in other languages. Packages area way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to the functionality. By organizing our classes into packages we achieve the following benefits: 1. The classes contained in the packages of other programs can be easily reused 2. In packages classes can be unique compared with classes in other packages. That is two classes in two different packages can have the same name. They are anyways referred by package name and the class name.
The sub directory name must match the package name exactly.
69
String Name; protected String DOB; public String Add; public Student(int x,String n,String d,String a) { RollNo=x; Name=n; DOB=d; Add=a; } public void display() { System.out.println("Display called from Student :"); System.out.println("Roll No :" + RollNo); System.out.println("Name :" + Name); System.out.println("Date of Birth :" + DOB); System.out.println("Address :" + Add); } } package Report; class Test extends Student { int m1,m2; Test(int x,String n,String d,String a,int y,int z) { super(x,n,d,a); m1=y; m2=z; } public void display() { super.display(); System.out.println("Display called from Test :"); System.out.println("Name :" + Name); System.out.println("Date of Birth :" + DOB); System.out.println("Address :" + Add); System.out.println("Marks 1 :" + m1); System.out.println("Marks 2 :" + m2); } } package SReport; import Report.Student; public class Sports extends Student { int score; public Sports(int x,String n,String d,String a,int s)
70
{ super(x,n,d,a); score=s; } public void display() { super.display(); System.out.println("Display called from Sports :"); //System.out.println("Roll No :" + RollNo); //System.out.println("Name :" + Name); System.out.println("Date of Birth :" + DOB); System.out.println("Address :" + Add); System.out.println("Sports score :" +score); } } package Report; class Result extends Test { int total; Result(int x,String n,String d,String a,int y,int z) { super(x,n,d,a,y,z); } public void display() { super.display(); System.out.println("Display called from Result :"); System.out.println("Name :" + Name); System.out.println("Address :" + Add); System.out.println("Marks 1 :" + m1); System.out.println("Marks 2 :" + m2); System.out.println("Total Marks :" + (m1+m2)); } } package Report; import SReport.Sports; class Demo { public static void main(String args[]) { Result R =new Result(1,"Shalini","01/01/1975","Vashi",65,75); R.display(); Sports s =new Sports(2,"Amar","01/01/1972","NaviMumbai",60); S.display(); } }
71
/*C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Student.java C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Test.java C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Result.java C:\Program Files\Java\jdk1.6.0_05\bin>javac SReport/Sports.java C:\Program Files\Java\jdk1.6.0_05\bin>javac Report/Demo.java C:\Program Files\Java\jdk1.6.0_05\bin>java Report/Demo Display called from Student : Roll No :1 Name :Shalini Date of Birth :01/01/1975 Address :Vashi Display called from Test : Name :Shalini Date of Birth :01/01/1975 Address :Vashi Marks 1 :65 Marks 2 :75 Display called from Result : Name :Shalini Address :Vashi Marks 1 :65 Marks 2 :75 Total Marks :140 Display called from Student : Roll No :2 Name :Amar Date of Birth :01/01/1972 Address :NaviMumbai Display called from Sports : Date of Birth :01/01/1972 Address :NaviMumbai Sports score :60*/
abs(float) abs(double) acos(double) asin (double) atan(double) atan2(double,do uble) ceil(double) cos(double) exp(double) floor(double) log(double) max(int, int) max(long, long) max(float, float) max(double, double) min(int, int) min(long, long) min(float, float) min(double, double) pow(double, double) random()
Returns the absolute float value of a. Returns the absolute double value of a. Returns the arc cosine of a, in the range of 0.0 through Pi. Returns the arc sine of a, in the range of -Pi/2 through Pi/2. Returns the arc tangent of a, in the range of -Pi/2 through Pi/2. Converts rectangular coordinates (a, b) to polar (r, theta). Returns the "ceiling" or smallest whole number greater than or equal to a. Returns the trigonometric cosine of an angle. Returns the exponential number e(2.718...) raised to power of a. Returns the "floor" or largest whole number less than or equal to a. Returns the natural logarithm (base e) of a. Takes two int values, a and b,& returns the greater number of the two. Takes two long values, a & b & returns the greater number of the two. Takes two float values, a & b& returns the greater number of the two. Takes two double values, a & b, & returns the greater number of the two. Takes 2 int values, a & b, & returns the smallest number of the two. Takes 2 long values, a & b, and returns the smallest number of the two Takes 2 float values, a &b, and returns the smallest number of the two. Takes two double values, a and b, and returns the smallest number of the two. Returns the number a raised to the power of b. Generates a random number between 0.0 and 1.0. Random number generators are often referred to as pseudorandom number generators because the numbers produced tend to repeat themselves after a period of time. Converts a double value into an integral value in double format Rounds off a float value by first adding 0.5 to it and then returning the largest integer that is less than or equal to this new value. Rounds off a double value by first adding 0.5 to it and then returning
rint(double) round(float)
round(double) sin(double)
the largest integer that is less than or equal to this new value. Returns the trigonometric sine of an angle.
73
sqrt(double) tan(double) E PI
Returns the square root of a. Returns the trigonometric tangent of an angle. The float representation of the value E. The float representation of the value Pi.
13.2.3 The java.util.Vector: Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as elements are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. Setting the capacity to what you want before inserting a large number of objects will reduce the amount of incremental reallocation. You can safely ignore the capacity and the vector will still work correctly. capacityIncrement elementCount Vector(int, int) Vector(int) Vector() addElement(Object) capacity() copyInto(Object[]) elementAt(int) removeAllElements() removeElement(Object) removeElementAt(int) The size of the increment. The number of elements in the buffer. Constructs an empty vector with the specified storage capacity and the specified capacityIncrement. Constructs an empty vector with the specified storage capacity. Constructs an empty vector. Adds the specified object as the last element of the vector. Returns the current capacity of the vector. Copies the elements of this vector into the specified array. Returns the element at the specified index Removes all elements of the vector. Removes the element from the vector. Deletes the element at the specified index.
13.2.4 The java.util.Random Random class generates a stream of pseudo-random numbers. To create a new random number generator, use one of the following methods:
new Random() new Random(long seed)
The form new Random() initializes the generator to a value based on the current time. The form new Random(long seed) seeds the random number generator with a specific
74
initial value; use this if an application requires a repeatable stream of pseudo-random numbers. The random number generator uses a 48-bit seed, which is modified using a linear congruential formula. The generator's seed can be reset with the following method:
setSeed(long seed)
To create a pseudo-random number, use one of the following functions: Random() Random(long) nextDouble() nextFloat() nextGaussian( ) nextInt() nextLong() setSeed(long) Creates a new random number generator. Creates a new random number generator using a single long seed. Generates a pseudorandom uniform ally distributed double value between 0.0 and 1.0. Generates a pseudorandom uniformally distributed float value between 0.0 and 1.0. Generates a pseudorandom Gaussian distributed double value with mean 0.0 and standard deviation 1.0. Generates a pseudorandom uniformally distributed int value. Generate a pseudorandom uniformally distributed long value. Sets the seed of the random number generator using a single long seed.
13.2.5 java.util.hashtable,: Hashtable class.maps keys to values. Any object can be used as a key and/or value. To sucessfully store and retrieve objects from a hash table the object used as the key must implement the hashCode() and equals() methods. This example creates a hashtable of numbers. It uses the names of the numbers as keys:
Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3));
Constructs a new, empty hashtable with the specified initial capacity and the specified load factor. Constructs a new, empty hashtable with the specified initial 75
capacity. Constructs a new, empty hashtable. Clears the hash table so that it has no more elements in it. Returns true if the hashtable contains no elements Puts the specified element into the hashtable, using the specified key. Returns an enumeration of the hashtable's keys. Rehashes the content of the table into a bigger table. Removes the element corresponding to the key. Returns the number of elements contained in the hashtable.
clone() Creates a clone of the hashtable. contains(Object) Returns true if the specified object is an element of the hashtable. containsKey(Object) Returns true if the collection contains an element for the key. 13.2.6 The java.util.Date,: A wrapper for a date. This class lets you manipulate dates in a system independent way. To print today's date use:
Date d = new Date(); System.out.println("today = " + d);
The date can be set and examined according to the local time zone into the year, month, day, hour, minute and second. Date() Date(int, int, int) UTC(int, int, int, int, int, int) getDate() getDay() getHours() getMinutes() getMonth() getSeconds() getTime() getYear() after(Date) before(Date) setDate(int) setDay(int) setHours(int) Creates today's date/time. Creates a date. Calculates a UTC value from YMDHMS. Returns the day of the month. Returns the day of the week. Returns the hour. Returns the minute. Returns the month. Returns the second. Returns the time in milliseconds since the epoch. Returns the year after 1900. Checks whether this date comes after the specified date. Checks whether this date comes before the specified date. Sets the date Sets the day of the week. Sets the hours.
76
Sets the minutes. Sets the month. Sets the seconds. Sets the time. Sets the year.
77
78
Misspelling of identifiers and keywords Missing double quotes in strings Use of undeclared variables Incompatible type in assignments / initialization Bad reference to objects Run Time errors: A program may compile successfully creating a .class file but may not run properly. Such programs may produce wrong results due to wrong logic or may terminate such as stack overflow. Most common run time errors are: Dividing an integer by zero. Accessing an element that is out of bound of in an array. Trying to store a value into an array of an incompatible class or type. Passing a parameter that is not in a valid range or value for a method Attempting to use a negative size for an array Use a null object reference as a legitimate object reference to access a method or a variable Converting an invalid string into a number When such errors are encountered, Java typically generates an error message and aborts the program.
14.2 Exceptions:
An exception is a condition that is caused by a run time error in the program. When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it. If the exception object is not caught and handled properly, the interpreter will display an error message as shown in the output of program and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This is called as exception handling. The purpose of exception handling mechanism is to provide a means to detect and report an exceptional circumstance so that appropriate action can be taken. The
79
mechanism suggests incorporation of a separate error handling code that performs the following tasks: 1. Find the problem (Hit the Exception) 2. Inform that an error has occurred (Throws the exception) 3. Receive the error information (Catch the exception) 4. Take the corrective actions (Handle the exception) The error handling code basically consists of two segments one to detect errors and to throw exceptions and other to catch exceptions and to take appropriate actions. While writing programs we must always be on the look out for places in the program where an exception could be generated. Some common exceptions that we must watch out for catching are listed in the table: Exception type ArithmeticException ArrayIndexOutOfBoundException ArrayStoreException FileNotFoundException IOException NullPointerException NumberFormatException OutOfMemoryException SecurityException StackOverflowException StringIndexOutOfBoundsExceptio n Syntax of Exception Handling code: try Block { Statement that causes the exception } Prof. Shalini Puri 80 Cause of Exception Caused by Math errors such as divide by zero Caused by error indexes Caused when a program tries to store wrong data in array Caused by an attempt to access a nonexistent file Caused by general I/O failures such as inability to read from a file Caused by referencing a null object Caused when conversion between strings and number fails Caused when there is not enough memory to allocate a new object Caused when an applet tries to perform action not allowed by browsers security Caused when the system runs out of stack space Caused when a program attempts to access a nonexistent character position in a string
Catch Block { Statement that handles the exception } Java uses a keyword try to prefer a block of code that is likely to cause an error condition and throw an exception. A catch block defined by the keyword catch catches the exception thrown by the try block and handles it appropriately. The catch block is added after the try block. 14.2.1 Arithmetic Exception: class Error { public static void main(String args[]) { int a=10,b=5,c=5,x,y; try { x=a/(b-c); } catch(ArithmeticException e) { System.out.println("Divide by zero"); } y=a/(b+c); System.out.println("y = " +y); } } /*Divide by zero y = 1*/ 14.2.2 Catching Invalid Command line arguments: class ClineInput { public static void main(String args[]) { int invalid=0,count=0,num; for(int i=0;i<args.length;i++) { try { num=Integer.parseInt(args[i]); }
81
catch(NumberFormatException e) { invalid++; System.out.println("Invalid arguments :"+args[i]); continue; } count++; } System.out.println("Valid arguments :"+count); System.out.println("InValid arguments :"+invalid); } } /*C:\Java\jdk1.5.0_04\bin>javac ClineInput.java C:\Java\jdk1.5.0_04\bin>java ClineInput Java 10 17.5 18 you Invalid arguments :Java Invalid arguments :17.5 Invalid arguments :you Valid arguments :2 InValid arguments :3*/ 14.2.3 Catch multiple exceptions It is possible to have more than one catch statement in the catch block as illustrated below: try { statement; } catch(ExceptionType1 e) { statement; } catch(ExceptionType2 e) { statement; } catch(ExceptionType3 e) { statement; } .. When an exception in a try block is generated, Java treats the multiple catch
82
statements like cases in switch statement. The first statement whose parameter matches with the exception object will be executed and the remaining statements will be skipped. class Error { public static void main(String args[]) { int a[]={5,10}; int b=5; try { int x = a[2]/b-a[1]; } catch(ArithmeticException e) { System.out.println("Division byb zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array Index Error"); } catch(ArrayStoreException e) { System.out.println("Wrong Datatype"); } int y=a[1]/a[0]; System.out.println("y= "+y); } } /*C:\Java\jdk1.5.0_04\bin>javac Error.java C:\Java\jdk1.5.0_04\bin>java Error Array Index Error y= 2*/ 14.2.4 The finally keyword Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch block shown as follows: try { } Prof. Shalini Puri 83
catch(..) { .. } catch(..) { .. } finally { .. } 14.2.5 Throwing our Exception: There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwable_subclass example: throw new ArithmeticException( ) ; throw new NumberFormatException( ) ;
84
15. Multithreading
Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms (processes) which can be implemented at the same time in parallel. For example one subprogram can display an animation on the screen while another may build the next animation to be displayed. This is something similar to dividing a task into subtasks and assigning them to different people for execution independently and simultaneously. Multithreading is a powerful programming tool that makes java distinctly different from its fellow programming languages. Multithreading is useful in a number of ways. It enables programmers to do multiple things at one time. They can divide a long program (containing operations that are conceptually concurrent) into threads and execute them in parallel. For example we can send tasks such as printing into the background and continue to perform some other task in the foreground. This approach would considerably improve the speed of other programs.
85
responsible for executing the main routine of the program. The main thread can in turn create other threads that can continue even after the main thread has terminated. The above figure illustrates four threads one main thread and three others. The main thread is designed to create other three threads namely A,B and C. Once initiated by the main thread the threads A,B and C run currently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency. Since threads in java subprograms of a main application program and share the same memory space they are known as lightweight threads or light weighted processes.
86
public void run( ) { .. . } When we start the new thread, Java calls the threads run() method, so it is the run() where all the action takes place. Starting New Thread: To actually create and run an instance of our thread class, we must write the following: MyThread athread = new MyThread( ); athread.start( ); The first line instantiates a new object of class MyThread. Note that this statement just creates the object. The thread is in a newborn state. The second line calls the start( ) method causing the thread to move into the runnable state. Then the java runtime will schedule the thread to run by invoking its run( ) method. Now the thread is said to be in running state. The below program illustrates an example extending the Thread class. class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("From Thread A : i ="+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("From Thread B : j ="+j); } System.out.println("Exit from B"); } }
87
class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("From Thread C : k ="+k); } System.out.println("Exit from C"); } } class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } } /*C:\Java\jdk1.6.0_05\bin>javac ThreadTest.java C:\Java\jdk1.6.0_05\bin>java ThreadTest From Thread A : i =1 From Thread A : i =2 From Thread A : i =3 From Thread A : i =4 From Thread A : i =5 Exit from A From Thread B : j =1 From Thread B : j =2 From Thread B : j =3 From Thread B : j =4 From Thread B : j =5 Exit from B From Thread C : k =1 From Thread C : k =2 From Thread C : k =3 From Thread C : k =4 From Thread C : k =5 Exit from C*/ 15.2.2 Implementing Runnable Interface: The runnable interface defines a single method, public void run ( ) that is required for implementing threads in our programs. The run( ) method is the entry point for the new thread. It makes up the entire body of the thread and is the only method in which the
88
threads behavior can be implemented. The run( ) method can call other methods use other classes and declare variables just like the main thread can. We must perform the steps listed below: Step 1: Declare the class as implementing the Runnable interface. Step 2: Implement the Run( ) method. Step 3: Pass an object that implements the Runnable interface as a parameter to the constructor of an object of type Thread. Step 4: Call the threads start( ) method to run the thread. When the threads start( ) method is called the thread will execute a call to run( ) method in the Runnable object. Following program illustrates implementation of the above steps: class NamedRunnable implements Runnable { private String Name; NamedRunnable(String name) { this.Name=name; } public void run() { for(int i=1;i<=10;i++) { System.out.println("Greetings from "+Name); } System.out.println("End of Child thread"); } } class RunnableTest { public static void main(String args[]) { NamedRunnable greetings = new NamedRunnable("Child thread"); Thread greetingsThread = new Thread(greetings); greetingsThread.start(); for(int i=1;i<=10;i++) { System.out.println("Main Thread"); } System.out.println("End of Main thread"); } /*C:\Java\jdk1.5.0_04\bin>javac RunnableTest.java C:\Java\jdk1.5.0_04\bin>java RunnableTest
89
Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread Greetings from Child thread End of Child thread Main Thread Main Thread Main Thread Main Thread End of Main thread*/
90
New Born
stop()
Active Thread Running yield yield() wait ( ) sleep() suspend( ) resume() notify () Runnable
stop()
Dead
stop( )
Blocked
If scheduled it moves to the runnable state. If we attempt to use any other method at this stage an exception will be thrown. Scheduling a newborn thread: NewBor n
Runnable State
Dead State
Runnable state: The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is the thread has joined the queue of threads that are waiting for execution. If all the threads have equal priority then they are given time slots for execution in round robin fashion i.e. first come first serve. The thread relinquishes control joins the queue at the end and again waits for its turn. The process of assigning time to threads is known as time slicing. However if we want a thread to relinquish control to another thread of equal priority before its turn comes we can do so by using the yield( ) method.
91
Running state: Running means that the processor has given its time to the thread for execution. The thread until it relinquishes control on its own or it is preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations. 1. It has been suspended using suspend ( ) method. A suspended thread can be revived by using the resume ( ) method. This approach is useful when we want to suspend a thread for some time due to certain reason but do not want to kill it. 2. It has been made to sleep. We can put a thread to sleep for a specified time period using the method sleep (time) where time is in milliseconds. This means that the thread is out of the queue during this time period. The thread re-enters the runnable state as soon as this period is elapsed. 3. It has been made to wait until some event occurs. This is done using the wait ( ) method. The thread can be scheduled to run again using the notify () method. Blocked state: A thread is said to be blocked when it is prevented from entering into the runnable state subsequently the running state. This happens when the thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered not runnable but not dead and therefore fully qualified to run again. Dead state: Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is natural death. However we can kill it by sending the stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born or while it is running or even when it is in not runnable condition
92
ThreadName.setPriority(intNumber); The intNumber is an integer value to which the threads priority is set. The thread class defines several priority constants: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 The intNumber may assume one of these constants or any value between 1 and 10. note that the default priority is NORM_PRIORITY. Most user level processes should use NORM_PRIORITY. Background processes such as network and I/O and screen repainting should use a value MIN_PRIORITY. By assigning priorities to threads we can ensure that we give them the attention they deserve. Whenever multiple threads are ready for execution the Java stream chooses the highest priority thread and executes it. The use of priority threads can be explained
15.5 Synchronization:
We have seen threads that use their own data and methods provided inside their run( ) methods. What happens when they try to use data and methods outside themselves? On such occasions they may compete for same resources they may lead to serious problem. For example one thread may try to read a record from a file while another is trying to read a record from a file while another is still writing to the same file. Depending on the situation we may get strange results. Java enables us to overcome the problem using a technique known as synchronization. The keyword synchronized helps us in keeping the watch on such locations. When we declare a method synchronized, Java creates a monitor and hands it over to the thread that calls the method first time. As long as the thread holds the monitor and hands it over to the thread that calls the first time. As long as the threads hold the monitor, no other thread can enter the synchronized section of the code. A monitor is like a key and the thread that holds the key can only open the lock. It is also possible to mark a block of code as synchronized as shown below: synchronized (lock object) {.. .}
93
Whenever a thread has completed its work of using synchronized method (or block of code), it will hand over the monitor to the next thread is ready to use the same resource. An interesting situation may occur when two or more threads are waiting to gain control of a resource. Due to some reason, the condition on which the waiting threads rely on to gain control does not happen. This results in a deadlock. For example assume that the threadA must access Method1 before it can release Method2 but the threadB cannot release Method until it gets hold of Method2. Because they are mutually exclusive conditions a deadlock occurs. The code below illustrates this: Thread A synchronized method2 ( ) { synchronized method1( ) { .. } } Thread B synchronized method1 ( ) { synchronized method2( ) { .. } }
94
The paint( ) method of the Applet class when it is called actually displays the result of the applet code on the screen. The output may be text, graphics or sound. The paint ( ) method which requires a Graphics object as argument, is defined as follows: public void paint (Graphics g) This requires that the applet code imports the java.awt package that contains the Graphics class. All output operations of an applet are performed is using the methods defined in the Graphics class. The general form of applet code is shown below: import java.awt.*; import java.applet.*; public class appletclassname extends Applet { public void paint(Graphics g) { .. .. } . } The appletclassname is the main class for the applet. When the applet is loaded, Java creates an instance of this class and the n series of Applet class methods are called on that instance to execute the code. The program shows a simple Hello.java applet. import java.awt.*; import java.applet.*; public class HelloJava extends Applet { public void paint(Graphics g) { g.drawString("Hello Java",10,100); } } <HTML> <APPLET CODE ="HelloJava.class" WIDTH = 400 HEIGHT = 200> </APPLET> </HTML>
96
The applet contains only one executable statement: g.drawString("Hello Java",10,100); hich when executed draws the string Hello Java at the position 10,00 (pixels) of the applets reserved space.
start() Runnin g paint() stop()Idle stopped destroy() End Browser Initialization state: Applet enters the initialization state when it is first loaded. This is achieved by calling the init( ) method of Applet class. The applet is born. At this stage, we may do the following if required. Create objects needed by the applet Set up initial values Load images or fonts Dead Destroyed Exit of
97
Set up colors
The initialization occurs only once in the applets life. To provide any of the behaviors mentioned above, we must override the init( ) method: public void init( ) { . . } Running state: Applet enters the running state when system calls the start( ) method of Applet class. This occurs automatically after the applet is initialized. Starting can also occur if the applet is already in stopped (idle) state. For ex: we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Note that unlike init( ) method, the start ( ) method may be called more than once. We may override the start() method to create a thread to control the applet. public void start( ) { . . } Idle or Stopped State: An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop( ) method explicitly. If we use a thread to run the applet then we must use stop( ) method to terminate the thread. We can achieve this by overriding stop( ) method public void stop( ) { . . } Dead state: An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when we quit the browser. Like initialization destroying stage occurs once in the applets life cycle. If the applet has created any resources like threads we may override the destroy() method to clean up these resources. public void destroy( )
98
{ . . } Display State: Applet moves to display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint() is called to accomplish this task. Almost every applet will have a paint() method. Like other methods in the life cycle the default version of paint() method does absolutely nothing. We must therefore override this method if we want anything to be displayed on the screen. public void paint( ) { . . }
99
The simplest shape we ca draw with the Graphics class is a line. The drawLine() method takes two pair of coordinates (x,y1) and (x2,y2) as arguments and draws a line between them. For example the following statement draws a straight line from the coordinate point (10,10) to (50,50): g.drawLine(10,10,50,50); The g is the Graphics object passed to paint() method. We can draw a rectangle using the drawRect() method. This method takes four arguments. The first two represent the x and y coordinates of the top corner of the rectangle and the remaining two represent the width and height of the rectangle. For example the statement g.drawRect(10.60,40,30); The drawRect () method draws only the outline of the box. We can draw a solid box by using the method fillRect(). This also takes four parameters corresponding to the starting point the width and height of the rectangle. For example the statement: g.fillRect(60,10,30,80); We can also draw rounded rectangles using the methods drawRoundRect() and fillRoundRect(). These two methods are similar to drawRect() and fillRect() except that they take two extra arguments representing the width and height of the angle of corners. These extra parameters indicate how much of corners will be rounded. Example: g.drawRoundRect(10,100,80,50,10,10); g.fillRoundRect(10,100,80,50,0,10); Circles and Ellipses: The Graphics class does not have any method for circles or ellipses. However the drawOval() method can be used to draw a circle or an ellipse. The drawOval() method takes four arguments the first two represent the top left corner of the imaginary rectangle and the other two represent the width and height of the oval itself. If the width and height is the same then the oval turns into a circle. The drawOval() method draws the outline of the Oval and the fillOval() method draws a solid oval. g.drawOval(20,20,200,120); g.fillOval(70,30,100,100);
100
Drawing arcs: An arc is part of an Oval. The drawArc() designed to draw arcs takes six arguments. The first four are the same as the arguments of the oval and the next two arguments specify the starting angle of the arc and the number of degrees around the arc. In drawing arcs, Java actually formulates the arc as an Oval and then draws only part of it as dictated by the last two arguments. Java considers the three O clock position as zero degree position and degrees increase in anti-clockwise direction. So to draw an arc from12.00 Oclock position to 6.00 oclock position, the starting angle would be 90 and the sweep angle would be 180. We can also draw an arc in backward direction by specifying the sweep angle as negative. We can use fillArc() method to fill the arc.
101
Ans : Already explained in 16.1 and 16.2. b) Write object oriented programs in Java to exemplify different types of visibility modifiers such as: Public, Protected, Private and Default. Ans: Already explained in 13.3. 2. a) Write an object oriented program in java that uses Euclids algorithm to display greatest common divisor of two integers. The greatest common divisor of two numbers is the largest number that divides both the numbers. Here is how the algorithm works: Find the remainder after dividing the larger number by smaller number using the modulus operator Change the larger number to the smaller number and change the smaller number to the remainder from step i) Keep doing this until the remainder is zero. Incorporate member functions for data input and displaying the result, default constructor and constructor with two parameters. Also create objects to reference the member functions. Ans: class great { int num1,num2; void getdata(int x,int y) { num1=x; num2=y; } int gcd() { Prof. Shalini Puri 102
if(num1<num2) { int temp=num1; num1=num2; num2=temp; } int r=1; while(r>0) { r=num1%num2; num1=num2; num2=r; } return(num1); } void putdata() { System.out.println(num1+ " " +num2+ " "+gcd()); } } class GCD { public static void main(String args[]) { great g =new great(); g.getdata(35,25); g.putdata(); } } /*E:\Java\jdk1.5.0_16\bin>javac GCD.java E:\Java\jdk1.5.0_16\bin>java GCD 35 25 5*/ b) Develop a Java program that determines the number of days in a given semester. Input data to the program consists of the year, month and day information of the first and last days of a semester. The program should accept the date information as a single string instead of accepting the year, month and day information separately. The input string must be in MM/DD/YYYY. Ans: import java.util.Calendar; class Demo { public static void main(String args[]) { Prof. Shalini Puri 103
System.out.println("Enter the starting date in MM/DD/YYYY:"); String S,SA; S=args[0]; String S1 = S.substring(0,2); String S2 = S.substring(3,5); String S3 = S.substring(6,10); int MM1=Integer.parseInt(S1); int DD1=Integer.parseInt(S2); int YY1=Integer.parseInt(S3); SA=args[1]; S1 = SA.substring(0,2); S2 = SA.substring(3,5); S3 = SA.substring(6,10); int MM2=Integer.parseInt(S1); int DD2=Integer.parseInt(S2); int YY2=Integer.parseInt(S3); Calendar C1 =Calendar.getInstance(); Calendar C2 =Calendar.getInstance(); C1.set(YY1,MM1,DD1); C2.set(YY2,MM2,DD2); System.out.println("No.of days in Semester :"+(C2.getTimeInMillis()C1.getTimeInMillis())/(24*60*60*1000)); } } /*C:\Java\jdk1.5.0_17\bin>java Demo 01/19/2009 04/30/2009 Enter the starting date in MM/DD/YYYY: 1 19 2009 4 30 2009 No.of days in Semester :100*/ 3. a) Write a Java program to compute the distance S fallen by an object in freefall. The formula is : S=S0+V0*t+1/2*a*t2 Ans: class Distance { public static void main(String args[]) { int S0=Integer.parseInt(args[0]); int V0=Integer.parseInt(args[1]); int a=Integer.parseInt(args[2]); int i=0,t; for(t=5;t<=100;i++) { System.out.println(); System.out.print("S"+i+":"); S0=S0+V0+(1/2)*a*(t*t); Prof. Shalini Puri 104
System.out.print(S0); t=t+5; } } } /*C:\Java\jdk1.5.0_17\bin>javac Distance.java C:\Java\jdk1.5.0_17\bin>java Distance 7 5 6 S0:12 S1:17 S2:22 S3:27 S4:32 S5:37 S6:42 S7:47 S8:52 S9:57 S10:62 S11:67 S12:72 S13:77 S14:82 S15:87 S16:92 S17:97 S18:102 S19:107 */ b) Write an object-oriented program to arrange names of students in descending order of their total marks. Input data consists of student details such as name, Id no and marks obtained in Mathematics, Physics and Chemistry. Use the concept of array of objects. Ans: import java.io.*; class Student { int RollNo; String Name; float maths,physics,chem,marks; void get(int a,String n,float m,float p,float c) { RollNo=a; Name=n; physics=p; maths=m; chem=c; marks=physics+chem+maths; } void put() { System.out.println(RollNo+ " "+Name+ " "+marks); } } class StudDetail { public static void main(String args[])throws IOException { Student s[]=new Student[5]; Student temp=new Student(); BufferedReader obj =new BufferedReader(new InputStreamReader(System.in)); String str; int x; float fp,fc,fm; int i,j; for(i=0;i<3;i++) Prof. Shalini Puri 105
{ s[i]=new Student(); } for(i=0;i<3;i++) { System.out.println("Enter Rollno :"); x=Integer.parseInt(obj.readLine()); System.out.println("Enter Name :"); str=obj.readLine(); System.out.println("Enter Physics :"); fp=Float.parseFloat(obj.readLine()); System.out.println("Enter Chemistry :"); fc=Float.parseFloat(obj.readLine()); System.out.println("Enter Maths :"); fm=Float.parseFloat(obj.readLine()); s[i].get(x,str,fp,fc,fm); } System.out.println("Student Details:"); for(i=0;i<3;i++) { s[i].put(); } System.out.println("Student Details in the descending order of marks:"); for(i=0;i<3;i++) { for(j=i+1;j<3;j++) { if(s[i].marks<s[j].marks) { temp=s[i]; s[i]=s[j]; s[j]=temp; } } } for(i=0;i<3;i++) { s[i].put(); } } } /*C:\Program Files\Java\jdk1.5.0_17\bin>java StudDetail Enter Rollno : 1 Enter Name : shalini
106
Enter Physics : 45 Enter Chemistry : 46 Enter Maths : 33 Enter Rollno : 2 Enter Name : ajay Enter Physics : 46 Enter Chemistry : 45 Enter Maths : 44 Enter Rollno : 3 Enter Name : abhi Enter Physics : 45 Enter Chemistry : 49 Enter Maths : 49 Student Details: 1 shalini 124.0 2 ajay 135.0 3 abhi 143.0 Student Details in the descending order of marks: 3 abhi 143.0 2 ajay 135.0 1 shalini 124.0*/ 4. following: 1. Overloading of functions: 2. Overriding functions: 3. Final methods and classes: Ans: A class can be declared final if its definition is complete and no subclasses are desired or required. A compile-time error occurs if the name of a final class appears in the extends clause of another class declaration; this implies that a final class cannot With the help of a suitable Java program describe the
107
have any subclasses. A compile-time error occurs if a class is declared both final and
abstract, final
class does not have any subclasses; the methods of a final class are never
overridden. There are two reasons for final methods. The first is to put a lock on the
method to prevent any inheriting class from changing its meaning. This is done for
design reasons when you want to make sure that a methods behavior is retained during inheritance and cannot be overridden. The second reason for final methods is efficiency. If you make a method final, you are allowing the compiler to turn any calls to that method into inline calls. When the compiler sees a final method call, it can skip the normal approach of inserting code to perform the method call mechanism of pushing arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value and instead replace the method call with a copy of the actual code in the method body. This eliminates the overhead of the method call. It is implied that the Java compiler is able to detect these situations and choose wisely whether to inline a final method. However, its best to let the compiler and JVM handle efficiency issues and make a method final only if you want to explicitly prevent overriding.[ 4. Abstract methods and classes: Ans: Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are cases in which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes as abstract classes. In some cases, abstract classes constitute the top few levels of the hierarchy, for Example abstract class Shape with abstract method Draw() has two derived abstract class Shape2D & Shape3D inherits the method Draw() & also do not provide any implementation for it. Now we have normal classes Rectangle, Square & Circle inherits from Shape2D, and another group of classes Sphere, Cylinder & Cube inherits from Shape3D. All classes at the bottom of the hierarchy must override the abstract method Draw(). public abstract class Shape { //...Class implementation
108
public abstract void Draw(int x, int y) { //this method mustn't be implemented here. //If we do implement it, the result is a Syntax Error. } } public abstract class Shape2D : Shape { //...Class implementation //...you do not have to implement the the method Draw(int x, int y) } public class Circle : Shape2D { //here we should provide an implemetation for Draw(int x, int y) public override void Draw(int x, int y) { //must do some work here } } 5. a) Write a detailed note on exception handling in Java in terms of the following: Try-catch, The finally keyword, Catch multiple exceptions, The throws keyword throwing exception
Ans: Already explained in Section 14.2. b) With the help of a suitable program, explain multithreaded programming in terms of the following: 6. { Creating threads and extending the thread class. Stopping and blocking a thread Define lifecycle of a thread interface Matrix final static int M=5, N=5; void readMatrix() void displayMatrix(); void addMatrix(); void multMatrix(); void transposeMatrix(); Prof. Shalini Puri 109
} Implementing the preceding interface by using suitable Java class programs Ans: interface Matrix { final static int M=5, N=5; public void readMatrix(); public void displayMatrix(); public void addMatrix(int x[][]); public void multMatrix(int x[][]); public void transposeMatrix(); } class abc implements Matrix { int x[][]=new int[3][3]; public void readMatrix() { int k=1; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { x[i][j]=k; k++; } } } public void displayMatrix() { System.out.println("Displaying Matrix :"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { System.out.print(x[i][j]+ " "); } System.out.println(); } } public void addMatrix(int y[][]) { int z[][]= new int[3][3]; System.out.println("Displaying Addition Matrix :"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++)
110
{ z[i][j]=x[i][j]+y[i][j]; System.out.print(z[i][j]+ " "); } System.out.println(); } } public void multMatrix(int y[][]) { int z[][]= new int[3][3]; System.out.println("Displaying Multiplicated Matrix :"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { for(int k=0;k<3;k++) { z[i][j]+=x[i][k]+y[k][j]; } System.out.print(z[i][j]+ " "); } System.out.println(); } } public void transposeMatrix() { System.out.println("Displaying Transposed Matrix :"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { System.out.print(x[j][i]+ " "); } System.out.println(); } } } class abc1 { public static void main(String args[]) { abc a =new abc(); a.readMatrix(); a.displayMatrix(); a.transposeMatrix(); int k=1;
111
int z[][]=new int[3][3]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { z[i][j]=k; k++; } } a.addMatrix(z); a.multMatrix(z); } } /*E:\Java\jdk1.5.0_16\bin>javac abc1.java E:\Java\jdk1.5.0_16\bin>java abc1 Displaying Matrix : 123 456 789 Displaying Transposed Matrix : 147 258 369 Displaying Addition Matrix : 246 8 10 12 14 16 18 Displaying Multiplicated Matrix : 18 21 24 27 30 33 36 39 42*/ 7. Write notes on the following with the help of suitable program segments in Java: Vectors: Already explained in Section 10.5. Strings: Already explained in Section 10-.1 and 10.2. Packages: Already explained in Section 13.1 and 13.2. Interfaces: Already explained in Section 12.4.
17.2 Dec-2008
1. Ans: Already explained in Section 12.4. a) Explain life cycle of a thread.
112
b) Write a program in java to find nCr and nPr. Ans: class PComb { static int fact(int n) { if(n==0) return(1); else return(n*fact(n-1)); } public static void main(String args[]) { int n=Integer.parseInt(args[0]); int r=Integer.parseInt(args[1]); int P,C; P=fact(n)/fact(n-r); C=fact(n)/fact(r)*fact(n-r); System.out.println("P ="+P); System.out.println("C ="+C); } } /*C:\Java\jdk1.5.0_17\bin>javac PComb.java C:\Java\jdk1.5.0_17\bin>java PComb 7 5 P =2520 C =84*/ c) Explain JVM in brief. Ans: The JVM stands for Java Virtual Machine. An abstract computing machine, or virtual machine, JVM is a platform-independent execution environment that converts Java byte code into machine language and executes it. Most programming languages compile source code directly into machine code that is designed to run on a specific microprocessor architecture or operating system, such as Windows or UNIX. A JVM machine within a machine mimics a real Java processor, enabling Java bytecode to be executed as actions or operating system calls on any processor regardless of the operating system. For example, establishing a socket connection from a workstation to a remote machine involves an operating system call. Since different operating systems handle sockets in different ways, the JVM translates the programming code so that the two machines that may be on different platforms are able to connect. d) Write a program to demonstrate the sum of series for a given value of n. 1+1/2+1/3+..+1/n
113
Ans: class series { public static void main(String args[]) { float n=Float.parseFloat(args[0]); float i; float sum=0.0F; for(i=1.0F;i<=n;i++) { sum+=1/i; } System.out.println("Series ="+sum); } } /*C:\Java\jdk1.5.0_17\bin>javac series.java C:\Java\jdk1.5.0_17\bin>java series 7 Series =2.5928574*/ 2. a) Compare and contrast overriding and overloading method with examples Ans : Already explained in 12.3 Section and calling different body of the function by different names is function overloading. b) Write a program in Java for fitting a straight line through a set of points (xi,yi) where i = 1n. The straight line equation is y = mx +c and the values of m and c are given by: m = ((xi,yi) - (xi,) (yi) ) / n(xi,)2 -(yi)2 C= 1/n (yi - mxi) 3. following menus and submenus. b) Explain different types of Inheritance with suitable examples. Ans : Already explained in 12.1 and 12.2 Section. 4. from an array? Ans: Already explained in 10.5 Section. b) c) What are applications of wrapper classes? Assume that a bank maintains two kind of account for its customers. The saving Ans: Already explained in 9 Section. account provides compound interest and withdrawal facilities but no cheque book facility. The current account provides cheque book facility but no interest. Current account holders maintain a minimum balance and if the balance falls below this level a Prof. Shalini Puri 114 a) What is vector? How it is different a) Write a program to display the
service charge is imposed. Create a class account that stores customer name, account number and type of account. From this derive the classes current account and saving account to make them more specific to their requirements. Include the necessary method in order to achieve the following tasks: i) Accept deposit from a customer and update the balance. ii) Display the balance iii) Compute and deposit interest iv) Permit withdrawal and update the balance. v) Check for minimum balance, impose penalty, if necessary, and update the balance. Ans : 5. with different examples. Ans : Already explained in 14 Section b) Write a program to create multiple threads. Ans : Already explained in 15.2 Section. c) Write a program to check whether given string is palindrome or not. Ans: class StringDemo { public static void main(String[] args) { String palindrome = args[0]; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); } // reverse array of chars for (int j = 0; j < len; j++) { charArray[j] = tempCharArray[len - 1 - j]; } String reversePalindrome = new String(charArray); if(palindrome.equals(reversePalindrome)) System.out.println("palindrome"); else System.out.println("not a palindrome"); } } /*C:\Java\jdk1.5.0_17\bin>javac StringDemo.java a) Explain Java Exception Handling
115
C:\Java\jdk1.5.0_17\bin>java StringDemo MADAM palindrome C:\Program Files\Java\jdk1.5.0_17\bin>java StringDemo MADAMA not a palindrome*/ 6. interface to a package? Explain with examples? Ans : Already explained in 13.1 Section. b) Will the code compile? If not, why? If yes, write output. i) import circle class Import Class { public static void main(String args[]) { Circle.NewCircle nc =new circle.NewCircle(); System.out.println(Hello World); } } Ans: The program does not compile. It gives the following errors. C:\Java\jdk1.5.0_17\bin>javac "Import Class.java" Import Class.java:1: '{' expected class Import Class ^ Import Class.java:9: '}' expected ^ 2 errors C:\java\jdk1.5.0_17\bin>javac "Import Class.java" Import Class.java:5: package Circle does not exist Circle.NewCircle nc =new circle.NewCircle(); ^ Import Class.java:5: package circle does not exist Circle.NewCircle nc =new circle.NewCircle(); ^ 2 errors ii) int m = 10; int n = 7; while(m%n>=0) { m=m+1; n=n+2; } Ans: The program will compile but will get into an infinite state. c) Explain Type Conversion and Type Casting in Java with examples. Prof. Shalini Puri 116 a) How do you add a class or an
Ans : Type Casting refers to changing an entity of one data type into another. This is important for the type conversion in developing any application. If you will store an int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data, which has to be stored. In this example we will see that how to convert the data type by using type casting. In the given line of the code c = (char)(t?1:0); illustrates that if t which is Boolean type variable is true then value of c which is the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode value. But in this line c = (char)(t?'1':'0'); 1 is already given as a character which will be stored as it is in the char type variable c. c = (char)(t?'1':'0'); System.out.println("Value of c after conversion : " + c); class Casting { public static void main(String args[]) { float sum; int i; sum=0.0F; for(i=1;i<=10;i++) { sum=sum+1/(float)i; System.out.print(" i = "+i); System.out.println(" sum = "+sum); } } } /* i = 1 sum = 1.0 i = 2 sum = 1.5 i = 3 sum = 1.8333334 i = 4 sum = 2.0833335 i = 5 sum = 2.2833335 i = 6 sum = 2.4500003 i = 7 sum = 2.5928574 i = 8 sum = 2.7178574 i = 9 sum = 2.8289685 i = 10 sum = 2.9289684*/ 7. Write short notes on (Any four):-
a) HTML Applet tags : Already explained in 16.1. Prof. Shalini Puri 117
b) Parameter passing Applets : We can supply user defined parameters to an applet using <PARAM..> tags. Each <PARAM..> tag has a name attribute such as color and a value attribute such as red. Inside the applet code the applet can refer to that parameter by name to find its value. For example we can change the color of the text displayed to red by an applet by using a <PARAM> tag as follows: <APPLET .> <PARAM = color VALUE =red> </APPLET> Similarly we can change the text to be displayed by an applet by supplying new text to the applet through a <PARAM> tag as shown below: b) Abstract Methods and classes: Already explained in 4.4 of May 2008. c) Synchronization: Already explained in 15.5 Section. d) String Methods: Already explained in 10.2 Section.
118