Java 3 rd sem. 2012 aug.ASSIGNMENT
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Java 3 rd sem. 2012 aug.ASSIGNMENT

on

  • 800 views

 

Statistics

Views

Total Views
800
Views on SlideShare
800
Embed Views
0

Actions

Likes
0
Downloads
16
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Java 3 rd sem. 2012 aug.ASSIGNMENT Document Transcript

  • 1. NAME:- MOHD. SHAHNAWAZ ALAMROLL NO:-COURSE:-B.SC (IT)SEMESTER: - THIRDBOOK NO:- BT0074(OOPS WITH JAVA)SESSION:- SPRING 20121. Give the features of Java.The concept of Write-once-run-anywhere (known as the Platform independent) is one of theimportant key feature of java language that makes java as the most powerful language.Platform IndependentThe concept of Write-once-run-anywhere (known as the Platform independent) is one ofthe important key feature of java language that makes java as the most powerfullanguage. Not even a single language is idle to this feature but java is more closer tothis feature. The programs written on one platform can run on any platform provided theplatform must have the JVM.SimpleThere are various features that makes the java as a simple language. Programs areeasy to write and debug because java does not use the pointers explicitly. It is muchharder to write the java programs that can crash the system but we can not say aboutthe other programming languages. Java provides the bug free system due to the strongmemory management. It also has the automatic memory allocation and deallocationsystem.Object OrientedTo be an Object Oriented language, any language must follow at least the fourcharacteristics.
  • 2. Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed. Encapsulation: : It is the mechanism of combining the information and providing the abstraction. Polymorphism: : As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods. Dynamic binding : Sometimes we dont have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime.As the languages like Objective C, C++ fulfills the above four characteristics yet theyare not fully object oriented languages because they are structured as well as objectoriented languages. But in case of java, it is a fully Object Oriented language becauseobject is at the outer most level of data structure in java. No stand alone methods,constants, and variables are there in java. Everything in java is object even the primitivedata types can also be converted into object by using the wrapper class.RobustJava has the strong memory allocation and automatic garbage collection mechanism. Itprovides the powerful exception handling and type checking mechanism as compare toother programming languages. Compiler checks the program whether there any errorand interpreter checks any run time error and makes the system secure from crash. Allof the above features makes the java language robust.DistributedThe widely used protocols like HTTP and FTP are developed in java. Internetprogrammers can call functions on these protocols and can get access the files fromany remote machine on the internet rather than writing codes on their local system.PortableThe feature Write-once-run-anywhere makes the java language portable provided thatthe system must have interpreter for the JVM. Java also have the standard data sizeirrespective of operating system or the processor. These features makes the java as aportable language.
  • 3. DynamicWhile executing the java program the user can get the required files dynamically from alocal drive or from a computer thousands of miles away from the user just by connectingwith the Internet.SecureJava does not use memory pointers explicitly. All the programs in java are run under anarea known as the sand box. Security manager determines the accessibility options of aclass like reading and writing a file to the local disk. Java uses the public key encryptionsystem to allow the java applications to transmit over the internet in the secureencrypted form. The bytecode Verifier checks the classes after loading.PerformanceJava uses native code usage, and lightweight process called threads. In the beginninginterpretation of bytecode resulted the performance slow but the advance version ofJVM uses the adaptive and just in time compilation technique that improves theperformance.MultithreadedAs we all know several features of Java like Secure, Robust, Portable, dynamic etc; youwill be more delighted to know another feature of Java which is Multithreaded.Java is also a Multithreaded programming language. Multithreading means a singleprogram having different threads executing independently at the same time. Multiplethreads execute instructions according to the program code in a process or a program.Multithreading works the similar way as multiple processes run on one computer.Multithreading programming is a very interesting concept in Java. In multithreadedprograms not even a single thread disturbs the execution of other thread. Threads areobtained from the pool of available ready to run threads and they run on the systemCPUs. This is how Multithreading works in Java which you will soon come to know indetails in later chapters.InterpretedWe all know that Java is an interpreted language as well. With an interpreted languagesuch as Java, programs run directly from the source code.The interpreter program reads the source code and translates it on the fly intocomputations. Thus, Java as an interpreted language depends on an interpreter
  • 4. program.The versatility of being platform independent makes Java to outshine from otherlanguages. The source code to be written and distributed is platform independent.Another advantage of Java as an interpreted language is its error debugging quality.Due to this any error occurring in the program gets traced. This is how it is different towork with Java.Architecture NeutralThe term architectural neutral seems to be weird, but yes Java is an architecturalneutral language as well. The growing popularity of networks makes developers thinkdistributed. In the world of network it is essential that the applications must be able tomigrate easily to different computer systems. Not only to computer systems but to awide variety of hardware architecture and Operating system architectures as well. TheJava compiler does this by generating byte code instructions, to be easily interpreted onany machine and to be easily translated into native machine code on the fly. Thecompiler generates an architecture-neutral object file format to enable a Javaapplication to execute anywhere on the network and then the compiled code isexecuted on many processors, given the presence of the Java runtime system. HenceJava was designed to support applications on network. This feature of Java has thrivedthe programming language.2. How do you execute a Java program? Most often in your Java programs you will find a need to execute system DOS commands. You can execute any system commands that are OS specific and then read the output of the system command from your Java program for further processing within the Java program. This sample Java Program executes the dir command reads the output of the dir command prints the results. This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command. import java.io.*; public class doscmd
  • 5. {public static void main(String args[]){try{Process p=Runtime.getRuntime().exec("cmd /c dir");p.waitFor();BufferedReader reader=new BufferedReader(newInputStreamReader(p.getInputStream()));String line=reader.readLine();while(line!=null){System.out.println(line);line=reader.readLine();}}catch(IOException e1) {}catch(InterruptedException e2) {}System.out.println("Done");}
  • 6. }3. What are the different types of operators used in Java?Operators play an important role in Java. There are three kinds of operators in Java. They are (i)Arithmetic Operators (ii) Comparison / Relational Operators and (iii) Logical Operators3.2.1 Arithmetic OperatorsAddition, Subtraction, Multiplication, Division and Modulus are the various arithmeticoperations that can be performed in Java.Table 3.1: List of Arithmetic OperatorsOperator Meaning Use Meaning+ Addition op1+op2 Adds op1 and op2- Subtraction op1-op2 Subtracts op2 from op1* Multiplication op1*op2 Multiplies op1 and op2/ Division op1/op2 Divides op1 by op2% Modulus op1 % op2 Computes the remainder of dividing op1 by op23.2.2 Increment and Decrement OperatorsThe increment operator is ++ and decrement operator is –. This is used to add 1 to the value of avariable or subtract 1 from the value of a variable. These operators are placed either before thevariable or after the variable name. The example below shows the use of these operators.Figure 3.4: Program Compilation and RunningWhen the operator ++ is placed after the variable name, first the assignment of the value of thevariable takes place and then the value of the variable is incremented. This operation is alsocalled post increment. Therefore the value of y1 will remain as 5 and the value of x1 will be 6.When the operator is placed before the variable, first increment of the variable takes place andthen the assignment occurs. Hence the value x2 and y2 both will be 6. This operation is alsocalled as pre increment. Similarly – – operator can be used to perform post decrement and predecrement operations. If there is no assignment and only the value of variable has to beincremented or decremented then placing the operator after or before does not make difference.
  • 7. 3.2.3 Comparison OperatorsComparison operators are used to compare two values and give the results.Table 3.2: List of Comparison Operators in JavaOperator Meaning Example Remarks== Equal op1 = = op2 Checks if op1 is equal to op2!= Not Equal op1 != op2 Checks if op1 is not equal to op2< Less than op1 < op2 Checks if op1 is less than op2> Greater than op1 > op2 Checks if op1 is greater than op2<= Less than or equal op1 <= op2 Checks if op1 is less than or equal to op2>= Greater than or equal op1 >= op2 Checks if op1 is greater than or equal to op23.2.4 Logical OperatorsLogical operators are used to perform Boolean operations on the operands.Table 3.3: List of Logical Operators in JavaOperator Meaning Example Remarks&& Short-circuit AND op1 && op2 Returns true if both are true. If op1 is false, op2 will not be evaluated and returns false.|| Short-circuit OR op1 || op2 Returns true if anyone is true. If op1 is true, op2 will not be evaluated and returns true.! Logical unary NOT !op Returns true if op is false.& Logical AND Op1 & op2 Returns true if both are true. Always op1 and op2 will be evaluated.| Logical OR Op1 | op2 Returns true if anyone is true. Always op1 and op2 will be evaluated.4. What are the various character extraction functions available inJava?
  • 8. charAt( ) To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form: char charAt(int where) Here, where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the string. charAt( ) returns the character at the specified location. For example, char ch; ch = "abc".charAt(1); assigns the v0alue "b" to ch. getChars( ) If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring. The following program demonstrates getChars( ): class getCharsDemo { public static void main(String args[]) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf[] = new char[end - start]; s.getChars(start, end, buf, 0); System.out.println(buf); } } Here is the output of this program:
  • 9. demo getBytes( ) There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called getBytes( ), and it uses the default character-to-byte conversions provided by the platform. Here is its simplest form: byte[ ] getBytes( ) Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange. toCharArray( ) If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It has this general form: char[ ] toCharArray( ) This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result. 5. What are the various types of relationships?Java represents two types of relationships:- 1.IS-A relationship 2.HAS-A relationship IS-A Relationship:-In object oriented programming,the concept of IS-A is a totally based on Inheritance(extends) and Interface implementation(implements).It is just like saying "A is a B type of thing".For example ,5-Star is a chocolate,Subaru Impreza is a car etc. It is key point to note that you can easily identify the IS-A relationship .Wherever you see an extends keyword or implements keyword in a class declaration,then this class is said to be passed IS-A relationship. For Example:- class Car{
  • 10. // lots of complex work}class Impreza extends Car{//Impreza extends and thus inherit all methods from Car (except final and static)//Impreza can also define all his specific functionality}From the above code we can say "Car is a Vehicle","Impreza is a Car", this in turn reflects a transitiverelationship that "Impreza is a Vehicle".The relationship can be shown as below:-Arrow direction from subclass to super classHAS-A Relationship:-HAS-A relationship has nothing to do with Inheritance rather it is based on theusage of various variables and methods of other class.We can say "A HAS-A B if the code in class A hasreference to an instance of B".Make it more clear look at following example:-public class Car{}class Impreza extends Car{private Subaru_feature subaru_features;}As you can see Impreza HAS-A instance variable of type Subaru.That is we can say "Impreza HAS-ASubaru_feature ".Simply here Impreza has a reference type of Subaru_feature.Impreza can use thereference variable to invoke the subaru features without caring about the Subaru_feature code.HAS-Arelationship is indicated by following figure:-
  • 11. HAS-A relationship makes each and every class a specialist class.Making specialists classes has numerous benefits including reduction in bugs,easily tractable errors,Less complex code,reduction in code redundancy and most of code is easily understandable.The more specialist a class is the code reuse is even better.Its a good Object Oriented practice to use HAS-A relationship 6. Differentiate between errors and exceptions. An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or aNullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.) 7. Give the syntax for FilelnputStream and FileOutputStream classes.FileInputStream.readSyntax 1public native int read() throws IOExceptionReturnsthe next byte of data, or -1 if the end of the file is reached.DescriptionReads a byte of data from this input stream. This method blocks if no input is yet available.
  • 12. ExceptionsIOException if an I/O error occurs.Overrides read in class InputStreamFileOutputStream.FileOutputStreamSyntax 1public FileOutputStream( String name ) throws IOExceptionParametersname the system-dependent filename.DescriptionCreates an output file stream to write to the file with the specified name.ExceptionsIOException if the file could not be opened for writing.ExceptionsSecurityException if a security manager exists, its checkWrite method is called with thename argument to see if the application is allowed write access to the file. 8. What is an applet? Explain with an example.Applet is java program that can be embedded into HTML pages. Java applets runs on the javaenables web browsers such as mozila and internet explorer. Applet is designed to run remotelyon the client browser, so there are some restrictions on it. Applet cant access system resourceson the local computer. Applets are used to make the web site more dynamic and entertaining.Example programimport java.awt.*;import java.applet.*;public class HelloJavaProgram extends Applet{String str;Public void init()
  • 13. {str=getParameter (“String”);if(str==null)str=”Java”;str=”Hello” + str;}public void paint(Graphics g){g.drawString (str,10,100);}}Compile this program and the .class file will be generated.HTML file for HelloJavaProgram applet<html><head><title> Welcome to Java Applet </title></head><body><applet code=” HelloJavaProgram.class” width= 400 height=200><param name=”String” value=”Applet!”></applet></body></html>Save this file as HelloJavaParam.html and then run applet using the applet viewer as follows:appletviewer HelloJavaProgram.html9. Give the use of adapter class.In java programming language, adapter class is used to implement an interface having a set ofdummy methods. The developer can then further subclass the adapter class so that he canoverride to the methods he requires. Implementing an interface directly, requires to write all thedummy methods. In general an adapter class is used to rapidly construct your own Listenerclass to field events.Java programming language also have a design adapter named adapter. The Adapter designpattern is also used to join to two unrelated interfaces so that can work together. The jointbetween these two interfaces is termed as Adapter. This is something like the conversion ofinterface of one class into interface. This is done by using an Adapter.10. What is JDBC? Explain.
  • 14. JDBC is Java application programming interface that allows the Java programmers to accessdatabase management system from Java code. It was developed by JavaSoft, a subsidiary ofSun MicrosystemsJava Database Connectivity in short called as JDBC. It is a java API which enables the javaprograms to execute SQL statements. It is an application programming interface that defineshow a java programmer can access the database in tabular format from Java code using a setof standard interfaces and classes written in the Java programming language.JDBC has been developed under the Java Community Process that allows multipleimplementations to exist and be used by thesame application. JDBC provides methods for querying and updating the data in RelationalDatabase Management system such as SQL, Oracle etc.The Java application programming interface provides a mechanism for dynamically loading thecorrect Java packages and drivers and registering them with the JDBC Driver Manager that isused as a connection factory for creating JDBC connections which supports creating andexecuting statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is thebackbone of the jdbc architecture.Generally all Relational Database Management System supports SQL and we all know thatJava is platform independent, so JDBC makes it possible to write a single database applicationthat can run on different platforms and interact with different Database Management Systems.Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used foraccessing and managing database, but the difference is that JDBC is designed specifically forJava programs, whereas ODBC is not depended upon any language.In short JDBC helps the programmers to write java applications that manage these threeprogramming activities:1. It helps us to connect to a data source, like a database.2. It helps us in sending queries and updating statements to the database and3. Retrieving and processing the results received from the database in terms of answering toyour query.