Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JAVA PROGRAMMING SUBJECT CLASS UNIT SEMESTER STAFF NASC –BCA : JAVA PROGRAMMING : III BCA : III : 5 : S.SAVITHA & N.P.SHIJU UNIT-III: Arrays, Strings and Vectors – Interfaces: Multiple Inheritance – Packages: Putting Classes together – Multithreaded Programming. PART A 1. Array is a collection of values of the same data type referred by a common value. 2. An array initializer is a list of comma separated expressions surrounded by curly braces. 3. String class is defined in java.lang package. 4.String concatenation can be done with the help of + operator and using the concat() method. 5. Interfaces are similar to classes but they lack instance variables and their methods are declared without any body. 6. Defining a new class based on an existing class is called derivation. 7.Dynamic method dispatch is the way through which Java implements run-time polymorphism . 8. Define Package DEFINING A PACKAGE To create a package, include package command as the first statement in your program followed by the package name. package pkg ; Where pkg is the name of the package. PART B 1. Write a Program using One-dimensional arrays The general form of one-dimensional array is JAVA PROGRAMMING NASC –BCA type var-name[ ]; type is the data type of the each element that comprises the array. Ex – int marks[ ]; marks is a array variable, no array actually exists. The value of marks is set to null. A operator “new” is used to allocated space for an array. marks = new int[6]; marks refers to an array of 6 integers. The individual elements of the array can be accessed starting from the index or subscript 0. For Ex. class Student{ public static void main(String args[ ]){ int marks[ ] = new int[6]; marks[0] = 50; marks[1] = 55; marks[2] = 43; marks[3] = 61; marks[4] = 77; marks[5] = 58; System.out.println(“The marks scored in subject1 is :”+marks[0]); } An array initializer is a list of comma separated expressions surrounded by curly braces. The commas separated the values of the array elements. The array will be created large enough to hold exactly the number of elements you specify in the array initializer. Java strictly checks that you don’t store or reference values outside the range of the array. Java runtime will check to be sure that all array indices are in the correct range. 2. Explain Multi- dimensional arrays These are arrays within arrays. The multidimensional arrays are allocated in blocks. If it is an X by Y by Z three-dimensional matrix, then the storage required will be X times Y times Z times the size of the type stored in each cell. In Java you can declare a variable to be three- dimensional but leave out the second and the thIrd dimension then allocate the Y and Z directions separately. Ex double matrix [ ] [ ] = new double [4] [4]; JAVA PROGRAMMING NASC –BCA matrix[0] = new double[4]; matrix[1] = new double[4]; matrix[2] = new double[4]; matrix[3] = {0,1,2,3}; Ex class Exarray{ public static void main(String args[ ]){ int twodim = new int [4] [5]; int I, j, k = 0; for(i = 0; i < 4 ; i++ ){ for(j = 0 ; j<5; j++){ twodim[i][j] = k ; k++; } } for(i = 0; i < 4 ; i++ ){ for(j = 0 ; j<5; j++){ System.out.println( twodim[i][j] ) ; k++; } } } } 3. Short note on INTERFACES Interfaces are similar to classes but they lack instance variables and their methods are declared without any body. So interfaces can be called as Pure abstract classes. Once defined any number of classes can implement an interface. And one class can implement any number of interfaces. Any class that implements an interface must provide definition for the complete set of methods in the interface. Interfaces are designed to support dynamic method resolution at runtime. Defining an Interface The general form of the interface is access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname1 = value; JAVA PROGRAMMING NASC –BCA ………………………………. } access can be either public or not defined. If not defined the default is package access(i.e the interface is available only to the members that belong to the same package as that of the interface). name is the name of the interface. The methods doesn’t have any body and they just end with a semicolon. These methods are abstract methods. Variables in the interface are final and static which means that their value cannot be changed by the implementing class. These variables must be initialized with a constant value. Ex - of an interface interface Callback{ void call(int param); } 4. Note on METHOD OVERRIDING When a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.. When an overridden method is called within a subclass it will always refer to the version of the method defined by the subclass. The version of the method defined by the superclass will be hidden. class A { int i, j; A(int a, int b){ i = a; j = b; } void show(){ System.out.println(“ values of i and j : +i + “ “ +j ); } } class B extends A{ int k; B(int a, int b, int c){ super(a, b); k = c; } void show(){ System.out.println(“value of k:”+k); } JAVA PROGRAMMING NASC –BCA } class Override{ public static void main(String args[ ]){ B ob1 = new B(); Ob1.show(); } } When show() is invoked on an object of class B, the version of show() defined within B is used. This show() method in B overrides the show() in A. 5. Short note on STATIC main() method can be accessed even before creating any instance, we call it as a class method and to specify this we used the keyword static. Variables can also be declared as static, and when objects of the class is created, no copy of the static variable is made. And all instances share the same static variable. Static variables have certain restrictions 1. They can only call other static methods 2. They must only access static data 3. They cannot refer to this or super in any way. Ex – class Usestatic{ static int a = 3; static double b ; static void Sqroot(){ System.out.println(“value of a:” +a); System.out.println(“Square root of a:” +b); } static{ System.out.println(“Static block”); b = Math.sqrt(a); } public static void main(String args [ ]){ Sqroot(); } } JAVA PROGRAMMING NASC –BCA block consists of the statement that calculates the square root of a. This static block ie is called as static initializer. Then the main method invokes the method Sqroot(). The println statements refer to the static variables a and b . If we want to access the static members of the class outside it, then we have to refer to the members as follows classname.method(); classname.variable; ie the classname followed by dot operator and the member . class Usestatic{ static int a = 3; static double b ; static void Sqroot(){ System.out.println(“value of a:” +a); System.out.println(“Square root of a:” +b); } static{ System.out.println(“Static block”); b = Math.sqrt(a); } } public class Statex{ public static void main(String args [ ]){ Usestatic.Sqroot(); } } 6. Short note on SYNCHRONIZATION When two or more threads need to access a shared resource, they need some way to ensure that only one thread access the resource at a time. The process by which this is achieved is called as synchronization. Synchronization uses the concept of monitor(semaphore). Only one thread can own a monitor at a time. All other threads must wait for the monitor until the thread leaves the monitor. Using synchronized methods class Callme{ JAVA PROGRAMMING NASC –BCA void call(String msg){ System.out.println(msg); try { Thread.sleep(1000); }catch(InterruptedException e){ System.out.println(“Interrupted”); } } } class Caller implements Runnable { String msg ; Callme target ; Thread t ; public Caller(Callme targ , String s ){ target = targ ; msg = s ; t = new Thread(this); t.start(); } public void run(){ target.call(msg); } } class Synch{ public static void main(String args [ ]){ Callme target = new Callme(); Caller ob1 = new Caller(target , “Hello”); Caller ob2 = new Caller(target , “Synchronised”); } } In this program nothing stops the 2 threads from calling the same method on the same object at the same time. This is known as race condition as all the threads are racing to complete the method. To avoid this precede the method definition call with the keyword synchronized class Callme{ synchronized void call(String msg){ …… } } JAVA PROGRAMMING NASC –BCA PART C 1. Describe the STRING HANDLING String class is defined in java.lang package. The Format of string constructors are 1. String s = new String(); 2. String (char chars [ ]); The first constructor is used when you need to create an empty string. To create a String initialized by an array of characters the second constructor can be used You can specify a subrange of a character array with the following constructor String (Char chars [ ], int startindex, int numchars); STRING CONCATENATION String concatenation can be done with the help of + operator and using the concat() method. public class Democoncat{ public static void main(String args [ ] ){ String s1 = “10” ; String s2 = “I have” + s1 +”copies of my certificate” ; System.out.println(s2); } } output : I have 10 copies of my cerificate String concatenation with other data types public class Democoncat{ public static void main(String args [ ] ){ int s1 = 10 ; String s2 = “I have” + s1 +”copies of my certificate” ; System.out.println(s2); } } In the above ex, the int value is concatenated with the string and we get the output as I have 10 copies of my certificate. Using concat() JAVA PROGRAMMING NASC –BCA public class Democoncat{ public static void main(String args [ ] ){ String s1 = “concatenation” ; String s2 = “string” ; System.out.println(s2.concat(s1)); } } The output is : string concatenation . 3. Explain the CHARACTER EXTRACTION Methods for character extraction 1.charAt() This method is used to extract a single character directly from the a String. The form char charAt(int where) where is the index of the character which you want to get. This value must be non-negative. char ch; ch = “negative”.charAt(2); which will give the result as “g”. 2. getChars() This can be used when you need to extract more than one character at a time. The general form is void getChars(int sourceStart, int sourceEnd, char target [ ], int targetstart); sourceStart specifies the beginning index of the substring and sourceEnd specifies the index of the end of the substring. The character till the position sourceEnd – 1 will be in the substring. target [ ] is the name of the char array where your extracted characters or substring is placed and targetstart specifies the starting position of the array target [ ]. class getcharsDemo{ public static void main(String args [ ]){ String s = “This is a demo of the method”; int start = 10; int end = 4 ; char buf [ ] = new char[end – start ] ; JAVA PROGRAMMING NASC –BCA s.getchars(start, end, buf , 0); System.out.println(buf); } } The output is : demo 3. getBytes() This is an alternative to getChars() which stores characters in an array of bytes. It uses the default character-to-byte conversions by the platform. byte [ ] getBytes() ; 4. Explain an INHERITANCE Defining a new class based on an existing class is called derivation. The new class or derived class is called as the direct subclass of the class from which it is being derived. The original class is called as the base class as it forms the base for the definition of the derived class. The base class can also be called as super class. The inclusion of members of a base class in a derived class so that they are accessible in the derived class is called class Inheritance. If a base class member is not accessible in a derived class, then it is not an inherited member of the derived class. Objects of the derived class type will contain all the inherited members of the base class – both fields and methods Let us see a simple example for inheritance. A Son may have certain characteristics resembling his Father. In addition to that he will have his unique features. So we can say that the Son has derived certain features from his father which implies that Son can be called as a subclass of the superclass Father. The general declaration for a class that inherits a superclass is class subclass-name extends superclass-name{ body of the class } JAVA PROGRAMMING NASC –BCA Java doesn’t support multiple inheritance. It only supports multi-level inheritance. So we can specify only one super class for any sub class we create. With multi-level inheritance, we can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass. class Shape { int d1; int d2; public void setvalues(int dimen1, int dimen2 ){ d1 = dimen1; d2 = dimen2; } } class Triangle extends Shape { int ar ; public void area(){ ar = (d1 * d2 )/ 2; System.out.println("Area of triangle:"+ar); } } class Rectangle extends Shape{ int ar; public void area(){ ar = d1* d2; System.out.println("Area of rectangle :"+ar); } } public class Inher{ public static void main(String args [ ]){ Triangle t = new Triangle(); t.setvalues(10,10); Rectangle r = new Rectangle(); r.setvalues(5, 10); t.area(); r.area(); } } We have defined a class Shape and we have assigned the dimensions. The two subclass inherited from Shape are Rectangle and Triangle. We have a method setvalues() in the base class which can be used to assign the dimensions. This base class method is inherited in both the subclasses. ie We have invoked the same method with reference to the object of Triangle, where we pass the values for base and height. And in the case of rectangle the values for breadth and height are passed . JAVA PROGRAMMING NASC –BCA MULTI – LEVEL HIERARCHY As we know Java supports only multi-level hierarchy and not multiple inheritance. For ex, consider three classes A, B and C. ie It is not possible to declare as follows class A { datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } class B { datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } class C extends A,B{ datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } The above declaration is multiple inheritance of classes and is not supported by Java MULTI-LEVEL INHERITANCE JAVA PROGRAMMING NASC –BCA class A { datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } class B extends A{ datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } class C extends B{ datatype var1; datatype var2; returntype method1(list of parameters){ body of method } } This declaration is multi-level inheritance .Like, class A is the super class of B and class B is the super class of class C. So class B can access the members of A, and class C can access the members of B(of course only the public and protected members), which means that class C can access the members of A Example for multi-level inheritance class Box{ double width; double height; double depth; Box (double w, double h, double d){ width = w; height = h; depth = d; } public double vol(){ return (width * height * depth); } } class Boxweight extends Box{ JAVA PROGRAMMING NASC –BCA double weight; Boxweight(double w, double h, double d, double m){ super(w, h, d); weight = m; } } class Shipment extends Boxweight{ double cost; Boxweight(double w, double h, double d, double m, double c){ super(w, h, d, m); cost = c; } } public class Boxex{ public static void main(String args [ ] ){ Shipment s1 = new Shipment(10, 6, 8, 14, 20); Shipment s2 = new Shipment(9, 8,7,12, 10); System.out.println(“Volume of box1"+s1.vol()); System.out.println(“Volume of box2: “ +s2.vol()); } } 5. Explain ABSTRACT CLASSES Sometimes we will create a class without giving implementation for all methods. For ex- let us consider the example Shape. class Shape { int d1; int d2; public void setvalues(int dimen1, int dimen2 ){ d1 = dimen1; d2 = dimen2; } public void area(){ System.out.println(“Area not defined”); } } class Triangle extends Shape { int ar ; public void area(){ JAVA PROGRAMMING NASC –BCA ar = (d1 * d2 )/ 2; System.out.println("Area of triangle:"+ar); } } class Rectangle extends Shape{ int ar; public void area(){ ar = d1* d2; System.out.println("Area of rectangle :"+ar); } } public class Inher{ public static void main(String args [ ]){ Shape s = new Shape(); Triangle t = new Triangle(); t.setvalues(10,10); Rectangle r = new Rectangle(); r.setvalues(5, 10); t.area(); r.area(); } } In the superclass Shape there is no need to give the implementation for the method area() because it is not meaningful. Only in the subclasses we have a meaningful implementation by calculating the areas of the corresponding to the shapes triangle and rectangle. To declare a abstract method, the syntax is abstract return-type methodname(list of parameters); We will implement the above example with the use of abstract class which will make you clear the concept of abstract classes abstract class Shape { int d1; int d2; public void setvalues(int dimen1, int dimen2 ){ d1 = dimen1; JAVA PROGRAMMING NASC –BCA d2 = dimen2; } abstract void area(); } class Triangle extends Shape { int ar ; public void area(){ ar = (d1 * d2 )/ 2; System.out.println("Area of triangle:"+ar); } } class Rectangle extends Shape{ int ar; public void area(){ ar = d1* d2; System.out.println("Area of rectangle :"+ar); } } public class Inher{ public static void main(String args [ ]){ // Shape s = new Shape() ; illegal as we cannot instantiate an abstract class Triangle t = new Triangle(); t.setvalues(10,10); Rectangle r = new Rectangle(); r.setvalues(5, 10); t.area(); r.area(); } } Since the method area in superclass Shape doesn’t have any implementation, we have declared it as abstract.The class is declared abstract as it has got an abstract method. 6. Describe PACKAGES Packages are containers for classes that are used to keep the class namespace compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported in to a new class definition A Java source file may contain any one or all of the following four internal parts JAVA PROGRAMMING 1. 2. 3. 4. NASC –BCA A single package statement Any number of import statements A single public class declaration Any number of classes private to the package Consider a programmer has given a name “Sample” for the class he defines. If you define a class with the same name “Sample” a name collision occurs. You can avoid this name collision by defining your class Sample within a different package. So you can access the class within your package by specifying packagename.Sample. So the class inside your package is not accessible outside your package. Only the class members in the same package can access the class. DEFINING A PACKAGE To create a package, include package command as the first statement in your program followed by the package name. package pkg ; Where pkg is the name of the package. Any classes inside the file belong to the specified package. Java uses file system directories to store packages. i. e if you have a package say package Mypackage ; All the . class files for the classes you describe in Mypackage must be stored in a directory called Mypackage. There can be any number of files with the same package statement. You can also create a hierarchy of packages i.e package pkg1[.pkg2] [. pkg3] ; We can’t rename a package without renaming the directory in which the classes are stored. CLASSPATH two ways 1. You can go one hierarchy up by one level and try it as java Myspace.Interest or 2. You can set the Classpath as ; c:\Myspace; c:\java\classes ExPackage Myspace; public class Interest{ int n; float p ; float v; JAVA PROGRAMMING NASC –BCA public Interest(int n, float p, float r){ this.n = n; this.p = p; this.r = r; } public void calculate(){ System.out.println(“Interest”+(n*p*r)); } } IMPORTING PACKAGES In the java source file, the import statement occurs immediately following the package statements and before any class definitions. The general form is import pkg1.pkg2.(classname/*); You can either specify a explicit classname or a star which indicates that the system should import the entire package. For ex, we will use our Class Interest, which belongs to Myspace package. import Myspace ; public class Intdemo{ public static void main(String args[ ]){ Interest i = new Interest(4, 500, 2); i.calculate(); } } This example accesses the members of the class Interest in the package Myspace. So the package has to be imported before its class members are used. 7. Explain MULTI-THREADING In a multi-threading program we can execute more than one parts simultaneously. Each part of the program is called as a thread. Multithreading is a form of multitasking There are two forms of multi-threading. 1. Process-based multitasking 2. Thread-based multitasking Process based multitasking allows to run two or more programs concurrently. Process-based Program is the smallest unit of dispatchable code Thread-based Thread is the smallest unit of dispatchable code JAVA PROGRAMMING NASC –BCA Processes are heavyweight tasks Threads are lightweight and requires same and requires separate address address space. space Interprocess communication Interthread communication is inexpensive is expensive Context switching between programs is expensive Ex – we can run a compiler as open a notepad as well Context switching between threads is inexpensive Ex - We can format text as well as print it provided each task is described as a separate thread. OR Explain JAVA THREAD MODEL In single-threaded systems, when a thread blocks because it is waiting for some resource, the entire program stops running, This wastes CPU time. This drawback is overcome by multithreading. Here one thread can pause without stopping other parts of your program. The idle time can be utilized somewhere else. So when a thread blocks a Java program, only the single thread that is blocked pauses. All other threads continue to run. Thread states Running Sleep Blocked Suspend Ready Any number of threads can be in the ready state, whereas only one thread can be in the running state at a time. When a thread waits for some resources it is said to be in the blocked state. The JAVA PROGRAMMING NASC –BCA thread is said to be in sleep state if it is idle. One thread can suspend other thread’s activity which can be resumed later. Thread class and Runnable interface Java’s multithreading system is built upon the Thread class and the interface Runnable. The various methods defined by Thread class are method Description getName Obtain thread’s name getPriority Obtain thread’s priority isAlive To see if a thread is still running join Wait for a thread to terminate run Entry point for thread sleep Suspend a thread’s activity for a period of time start Start a thread by calling its run method The Main thread When a Java program starts one thread begins execution automatically . It is called the main thread of the program . It is the last thread to finish execution. class CurrentThreadDemo{ public static void main(String args [ ]){ Thread t = Thread.currentThread(); System.out.println(“Current thread :” +t); t.setName(“My thread”); System.out.println(“After name Change: “ + t); try{ for (int i = 5 ; i > 0 ; i-- ){ System.out.println(i); Thread.sleep(1000); } }catch(InterruptedException e){ System.out.println(“Main thread interrupted”); } } } JAVA PROGRAMMING NASC –BCA A reference to the current thread can be obtained by the method currentThread(). The default name for the thread is main and after name change it becomes My Thread. Creating a thread You can create a thread by instantiating an object of type Thread. It can be done by 2 ways 1. Extend Thread class 2. Implement Runnable interface class NewThread implements Runnable { Thread t ; NewThread() { t = new Thread(this, “Demo thread”); System.out.println(“Child thread “ + t); t.start() ; } public void run(){ try { for(int i = 5 ; i > 0 ; i -- ) { System.out.println(“Child thread :” + i) ; Thread.sleep(500); } }catch(InterruptedException e){ System.out.println(“Child thread interrupted “); } System.out.println(“child thread exit”); } } public class ThreadDemo { pubic static void main(String args [ ]){ new NewThread(); try { for(int i = 5 ; i > 0 ; i -- ) { System.out.println(“Main thread :” + i) ; Thread.sleep(1000); } }catch(InterruptedException e){ System.out.println(“Main thread interrupted “); } System.out.println(“Main thread exit”); } JAVA PROGRAMMING } The output will be Main thread : 5 Child thread : 5 Child thread : 4 Main thread : 4 Child thread : 3 Child thread : 2 Main thread : 3 Child thread : 1 Child thread Exit Main thread : 2 Main thread : 1 Main thread Exit NASC –BCA