You are on page 1of 17


1. Assignments on class, constructor, overloading, inheritance, overriding
2. Assignments on wrapper class, vectors, arrays
3. Assignments on developing interfaces- multiple inheritances, extending interfaces
4. Assignments on creating and accessing packages
5. Assignments on multithreaded programming, handling errors and exceptions, applet
programming and graphics programming
6. Use of CASE tools

Week 1:

What is Object-Oriented Programming?

Ans. : Our real world is full of objects. Living objects include birds, animals,
human etc. Objects without life include furniture, buildings, food, dress etc.
Each of these objects have certain properties. The properties of the objects
describe the state of the object. Certain operations can also be performed on
these objects. The operations that can be performed, describe the behavior of the
objects. For example, a bird has wings. It can fly. Humans have brain, legs.
They can walk, talk and think. Furniture have leg, arms. They can be moved
from one place to another place. Object – oriented programming involves
representing objects in a programming language and use them. C++, java,
SmallTalk, .NET are example of object-oriented programming language.

What are classes?

Ans.: A class represents a group of objects of the same kind. For example class of
animals represent – cow, dog, cat, tiger etc. A class is blue print or template for
creating multiple objects.

What are objects?
Ans.: An object is an instance of a class. For example Maruti is an instance of the
class car. Zen is another instance of the class Cars. So Maruti and Zen are
objects here. You can observe all the cars have similar features such as have
wheels, have break, have seat etc.

: A compiler converts the java program into an intermediate language representation called Bytecode which is platform independent. A java file will have extension .3\bin> javac firstClass. run anywhere” is possible in java. public class firstClass { public static void main(String[] args) { System.class 3.doc. The resulting bytecodes can then be run on Windows 98. The compiled java program can run on any hardware platform having Java Virtual Machine(JVM) install on it. import java.out. text file has the .java. Java platform consists of Java Virtual Machine (JVM) and a package of ready-made software components. c:\jdk1. Window’s 2000 or Solaris or Macintosh or any other machine.3/bin javac will convert it to bytecode.: Write the following program named firstClass. The concept of “write once.How JAVA works ? Ans.txt extension. This package is known as the Java Application Programming Interface (Java API). Then you find firstClass. c:\jdk1.println("Hi ! This is my First Program in Java") . The machine should have a Java platform to run Java code. like word file has . How you compile java program? Ans.*. } } 2.3\bin>java firstClass The following program is to input a int value from keyboard and display through edit and save it to jdk1. The Java program can be complied on any platform having a java . 1.

Example : 2 /* Program to add two number */ class AddNum{ public static void main(String args[]){ int a=10. } } Example: 3 /* Write a program to find largest of integer */ class Larg { public static void main(String args[]){ int x1=10.println(“x2 is larger than x1”). the type of the values stores in integer and the number of elements that can be store in the array is 10. if (x1>x2) System. else System. int x2=20. • Declare a variable to be used as the array name. This is also called dimension of the array.out.println(“x1 is larger than x2”). • Create an array object and assign to the variable.println(“Sum=”+sum). } } Array : Arrays are a means of storing a list of items. Multiple values of the same type can be stored together. System. Arrays can hold data of similar type. int sum=a+b. When the array is created initially all the values are . To use an array we require the following to be done.out. This creates an array with the name values.out. int values[]=new int[10]. int b=20.

6.initialized to zero. Arrays can contain any legal java data type including reference types such as objects or other arrays. . Or String str1[] = new String[10]. For example the first element of the above array is referred as values[0]. The individual elements of the array can be access by using an index with the array name.10}. String[] str1 = new String[10]. For example.7. int[][] myArray = new int[5][5]. Creating and initialization of an array can be done at the same time as follows: int[] values=new {5. second element is referred as values[1] and so on. Two dimensional arrays are used as follows.8.9. the following declares an array that can contain ten String objects.

out. When a member declare static.out.println("Syntex : cmdLineArgv val1 val2") .parseInt(args[1]). We can declare both member and variables to be static.Example 2.out.I<6. The most common example of a static is main(). Methods declared as static have several restrictions:  They can only call other static methods  They must only access static data.out. and without reference to any objects.exit(0) . System. However. int v=i+j. System. without reference to a specific instance. } int i=Integer.8. if (n !=2) { System. To create such a member.println(“Values[“+I+”] = “+values[I]). System.1 class ArrayUse{ public static void main(String args[]){ int[] values = {5. } } Example 2. } } What is static? Ans. it can be accessed before any objects of its class are created. When objects of its class are declared.7. main() is declare as static because it must be called before any objects exist. you mast convert it int j=Integer.9.2 //Program shows how to use command line argument public class cmdLineArgv { public static void main(String[] args) { int n = args.parseInt(args[0]). no copy of static variable is made. it is possible to create a member that can be used by itself.length .//In that case the all values of args are string. precede its declaration with the key static.6. essentially.10}.println("The Sum of "+args[0]+" & "+args[1]+" is "+v) . .println("Error Input") . Instance variables declared as static are. global variables. A class member must be accessed only in conjunction with an object.: There will be times when we will want to define a class member that will be used independently. all instance of the class share the same static variable. for(int I=0.I++) System.

point.println("The sum ="+z). } public class simpClass { public static void main(String[] args) { Point point = new Point(). x = 2. you will use a statement Point point = new Point(). In this case. A class defines a new type of data.x + point. To actually create a Point object. y and no method. } } Each object has its own copies of the instance variables. point.x = 10. the new data type is called Point . You will use this name to declare objects of type Point. It is important to remember that a class declaration only creates a template. To assign an variable point. it does not create an actual object. int z= point. each has its own copy of x & y.  They cannot refer to this or super in any way(The keyword super relates to inheritance) Simple Class Here is a class called Point that define two variable x . the following program declares two Point objects: . This means that if you have two Point objects. For example.3 //Program is a example of simple class class Point{ int x. Example 2. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another.y . int y.y = 20. System.out.

void displayValue(){ int x = 5.x = 5. point. int y = 10. point1. point1. The example below shows the use of this keyword. Example 2. System.y = 20. that is if it is not defined within the current method then java checks for the definition of that variable as an instance or class variable in the current class. If the definition is not found still then it is checked in each superclass in turn.println(x+y) . Point point1 = new Point(). Consider the case when same variable name is used for both local variable and instance or class variables. .addVal() . } } public class simpClass { public static void main(String[] args) { Point point = new Point(). If the variable is not local variable. } } A variable declared can be used only within the block it has been declared. Ver:") . class Point{ int x.out. However the value of instance or class variables can be accessed by using the keyword this along with the variable name. int y.out.out.addVal() .4 //Program declares two class and add a method. When a variable is referred within a method.x = 10.print("The sum is :") . point1. It has a limited scope within which it can be used. point. int z = 20. java checks for the definition of the variable within a current scope and then in the next outer scope and then up to the current method definition. void addVal(){ System. System.5 public class TestThis { int x =10. int y = 20.y = 30. point.Example 2. int z = 30.println("Printing Loc.

x +" "+this. But the number or type of arguments have to be different.out.  Constructor methods have the same name as the name of the class.out.out.println("Printing value in main()") .println(this. Constructor methods are written keeping the following points in mind.  There can be more than one constructor method. System. System. This is to be defined since it is overridden Circle(){ } Circle(int x1.y +" "+this. } public static void main(String[] args) { TestThis temp = new TestThis(). Example 3. System. System.out.displayValue() .2 // Program to show the use of constructors class Point{ int x.x +" "+temp. Point(int x1.println("Printing instance Veriable") .z ) .println(temp. int radius=3. int r) . // Default constructor. System. int y1) { x=x1.println(x+" "+y+" "+z+" ") .  Typically they are used as to set initial values to instance variables. int y. y=y1. int y1. Constructor methods are called automatically by java. int originY=5. temp.y+" "+temp. } } WEEK 2 Constructor Methods Constructor method is called when an object is created.z ) .out. } }// end of Point class class Circle{ int originX=5.

c2. class OverLoadMethod{ static float add(int x. { originX=x1.5).display().10).println(“Radius = “+radius). } public static void main(String args[]){ Circle c1=new Circle().println(“Center at “+originX+”and”+originY). OriginY=p.35). converts them to integer add then return sum as floating point number.out. System. The program below shows overloading of methods. } void display(){ System. } } Overloading Methods You can have same name for more than one y) { return x+y.display(). The return types of the methods can be different as long as the method signature is different. radius = r. } // Constructor taking first parameter as the type Point and the second as an int Circle(Point p. Circle c2=new Circle(10. radius=r.y. . originY=y1.out. The first add() takes integers as arguments and returns the sum as floating point number. The example below shows overloading of a method called add. c3.display(). The third ass() takes string as arguments.25. c1. int r){ OriginX=p.x. Example 3. The second add() takes floating point numbers as arguments and returns the sum as a floating point number. Circle c3=new Circle(new Point(15.1 // This program shows overloading of method. The number of arguments or the type of arguments are to be different for creating two or more methods with the same name.

String s2=”35”.out.out.5f.5f. In the example the method display() and this. float t2) { return t1+t2. then the super keyword can be used along with the name of the method. If it can not find. Consider the cause when the same method name is used in both the subclass and superclass with the same signature (same number of argument with the type) .println("From superclass:") . } static float add(float t1. float m = 5.n)). } public static void main(String args[]){ int x=10. It is now hidden for the objects of the subclass. } } Method overriding When an object’s method is called. } } .println(add(s1.println(add(x. System.out. System.out. return sum.display() will invoke method display() of the superclass. System.println(add(m.s2)). } static float add(String s1. sum = Integer.4 //Example for Method overriding public class superClass1 { void display() { System. Here when the method is called. If the method in the super class has to be used. String s2) { float sum.parseInt(s1)+Integer. float n = 10.parseInt(s2). The method defined in the super class is overridden. then it checks one level up in the hierarchy of classes. method defined in the subclass is invoked. Example 3. String s1=”25”. java looks for the method definition in the objects class. y=20.y)).

} }//End of superClass class SubClass extends superClass{//new Class subclass call superClass public static void main(String[] args) { SubClass s1 = new SubClass(). but also super class upwards. sum=x+y.//search locally first } public static void main(String[] args) { OverRide s1 = new OverRide().//From super class.display().class OverRide extends superClass1{ void access(){ System. } void disp() { System.println("From superclass") . this.out. In java only single inheritance is allowed that means classes can inherit methods only form one intermediate super class.display(). The keyword extends is used after the name of class. Here Class1 and Class2 are called subclasses and Class0 is called as super class . Inheritance provides a chain in which a class inherits not only from it’s immediate super class.access().out. The keyword extends is followed by the name of the super class. The concept of using methods and variables defined in another class is called as inheritance. System. display().println("Displays from a different place").println("Sum of two number is "+sum).out. Example 3. } } WEEK 3 Subclasses/Inheritance/Super class/Extends When more than one let us say Class1 and Class2 have some properties to be shared.// You call the subclass not superclass .// Search locally first super.3 //Example for Inheritance public class superClass { void addNum(int x. then they could be defined in a single class let us say Class0 as if they belonged to y){ int sum. s1.

try{ i=0.1 //Example Exception handling class Excep1{ public static void main(String args[]){ int i. It is basically a shorthand to indicate exceptional event.// Here you call the method of superClass. thereby allowing a method further up the call stack to catch it. The runtime system searches back words through the call stack. creating an exception object and handing it to the runtime system is called throwing an exception. Thus only the methods that care about errors have to worry about detecting errors.out. beginning with the method in which the error occurred.40). the method creates an exception object and hands it off to the runtime system.j. By using exceptions to manage errors.println(“Trying to division by zero…. Grouping or categorization of exceptions is possible. The exception object contains information about the exception.println(“The value of J=”+j). until it finds a method that contains an appropriate exception handler. The runtime system is then responsible for finding some code to handle the error. } } WEEK 4 Exception Handling The java language uses exceptions to provide error-handling capabilities for its programs. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. 1. including its type and the state of the program when the error occurred. s1. }catch(ArithmaticException ex){ System. 3. System. A java method can “duck” any exceptions thrown within it. java programs have the following advantages over traditional error management technique.”). 2. j=30/i.disp(). } }} . When such an event occurs within a Java method.addNum(10. Example 4. s1.out. In java terminology. It helps to separate the error handling code from the regular code.

. WEEK 5 Final class. NullPointerException Invalid use of null referance NumberFormatException Invalid conversion of a string to a numeric format SecurityException Attempt to violate security StringIndexOutOfBouds Attempt to index outside the bounds of string UnsupporteOperationException An unsupported operation was encountered. IllegalStateException Application is in incorrect state. ArryIndexOutOfBoundsException Array Index out of bound ArrayStoreException Assignment to an array element of an incompatible type.  A final class can not be sub classed. Final methods run efficiently. Variables are declared as final when their values do not change. IndexOutOfBoundsException Some type of index is out of bound NegativeArraySizeException Array Created with a negative size.  A final method cannot be overridden  A final variable cannot change its value. Build In Exception: Exception Description ArithmeticException Arithmetic errors. methods and variables The final modifier indicates that the entity can not be changed. IllegalThreadStateException Requested operation not compatible with current thread state. ClassCastException Invalid Cast IllegalArgumentException Illegal argument used IllegalMonitorStateException Illegal monitor operation. such as waiting on an unlocked thread. Java class library declares many of the commonly used methods final so that they can be executed more quickly. They are also defined as static since the constant values in a class will be generally class wide information.You can use “Exception” in replace of “ArithmaticException” or any other exception.

} abstract void printMSG(). Some of the subclass has to override it and provide the implementation. Math. } } WEEK 6 Stream: A stream is a path traveled by data in a program. . s1.lang. a program can send information to an external destination by opening a stream to be a destination and writing information out serially. a program opens a stream on an information source (a file. Abstract classes basically provide a guideline for the properties and methods of an object.println("Example for ABS class"). a memory.out.display(). they have to be sub classed. To bring in information. In order to use abstract classes. Similarly. If all the methods in the abstract classes are abstract that is without any implementation. } public static void main(String[] args) { TestABS s1 = new TestABS(). Many popular java classes such as java. An abstract method has no body.lang. java. then it is better to implement as an interface than as an abstract class.printMSG(). Objects cannot be created out of abstract classes.A final class cannot be sub classed by another class.String are final.out.println("From abstract class") . it means that zero or more of its methods are abstract.5 //Example for Method overriding abstract class AbstractClass { void display() { System. This gives some speed benefits. All methods in a final class are automatically final. Example 3.// abstract method } class TestABS extends AbstractClass{ void printMSG(){ System. s1. Abstract Classes When the keyword abstract appears in a class definition. a socket) and reads information.

println("IO Error") . This stream is already open and ready to supply input data.err : The “standard” error output stream.Using a Stream: No matter where the information is coming from or going to and no matter what type of data is being read or written.println("What is ur name ?") .out. This stream is already open and ready to accept output data. a) System.  Read/write data using the object’s read()/write() This is the “standard” c) System.out.out : The “standard”  Finally close the stream by calling close() method.2 //Simple program to input data through keyboard. Typically this stream corresponds to display output.lang. Typically this stream corresponds to keyboard input.System class. the algorithms for reading and writing data remain the same. } } } . The steps involved are. public class simpInput_1 { public static void main(String[] args) { byte name=new byte(60).write("UR name is "+name) . They are byte streams and character streams. try{ System.  Create an object of input/output stream that is associated with the data source/data destination. b) System. These classes are divided into two class hierarchies based on the data type on which they operate. import java. Example 4. These streams are declared in the package contains a collation of stream classes for doing this. System. Typically this stream corresponds to display output. and they are all byte streams. The java. }catch (IOException e){ System. System. This stream is already open and ready to accept output data.*.read(name) .out. Predefined Streams: There are three predefined streams already open and ready to use in every program.

out. }catch (IOException e){ System.IOException.3 //Enter name through keyboard using DataInputStream import java. byte. Example : 1 import"Value is :"+Integer.println("What is ur name ?") . .out. int.*. you can use dada input and data output streams. System.Data Streams Data Input Stream and Data Output Stream If you need to work with data that is not represented as bytes or"IO Error") .println("Please enter an Integer value ") .io. double.lang. float . import A data input stream is created with the DataInputStream(InputStream) constructor.String. )). Conversely.readLine() . } } Example 4. public class inputInt { public static void main(String[] args) throws IOException { BufferedReader keyBoardInput=new BufferedReader ( new InputStreamReader(System.BufferedReader. which indicates the associated output stream. int val1=Integer.toString(val1) ) . The argument should be existing input stream such as a buffered input stream.InputStreamReader.parseInt(keyBoardInput.out. System.println("UR name is "+name1) . try{ String name1=name. System. a data output stream requires the DataOutputstream(Output Stream) constructor. public class simpInput_1 { public static void main(String[] args) { DataInputStream name=new DataInputStream(System. import java. long and short. import java.readLine() ) .out.out. These streams filter an existing byte stream so that each of the following primitive types can be read or written directly from the stream :

compareTo(Object) .println(str1. //Output “mp” . compareTo(String) .out.length() ). ending position. } } } Some features of Stream: length() .4 String str1=”Computer”.println(substring(2.Returns 0 if equal. toUpperCase() -Return to block letter of a string.// Output “m” System.Returns a charter from a string at n’th position.println(charAt(2)). Example: 4.Returns 0 if equal. //output 8 System.out. substring(int. toLowerCase() -Return to lowercase of a .Give the starting position. System.count number of character of string charAt(int) .out.4)).