Beruflich Dokumente
Kultur Dokumente
JAVA
COMPLETED AT JUNE-JULY 2012 NARESH TECHNOLOGIES
SUBMITTED IN PARTIAL FULFILLMENT FOR AWARD OF DEGREE OF BACHELOR OF ENGINEERING IN
Bhanu Pratap Raj (0613CS091010) DEPARTMENT OF COMPUTER SCIENCE ENGINEERING Gyan Sagar College of Engineering, Sagar (M.P) August,2012
Page 1 of 38
CONTENTS
S.No. Title Page No.
1 2 3 4 5 6 7 8 9 10
Introduction to Java Data Types Object Oriented Features Polymorphism Static Keyword Inheritance Interfaces Multi Threading Scanner JDBC
Page 2 of 38
INTRODUCTION
Page 3 of 38
INTRODUCTION TO JAVA
Before starting to learn Java, let us plunge into its history and see how the language originated. In 1990, Sun Microsystems Inc. (US) has conceived a project to develop software for consumer electronic devices that could be controlled by a remote. This project was called stealth project but later its name was changed to Green project. In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton, and several others met in Aspen, Colorado to discuss was to begin work on the graphics system, and James Gosling was development, Patrick Naughton was to begin on the graphics system, and James Gosling was to identify the proper programming language for the project. Gosling thought C and C++ could be used to develop the project. But the problem he faced with them is that they were system dependent language and hence could not be used on various processors, which the electronic device might use. So he started developing a new languages, which was completely system independent. This language was initially called Oak. Since this name registered by some other company, later it was changed to Java. Why the name Java? James Gosling and his team members were consuming a lot of coffee while developing this language. They felt that they were able to develop a better language because of the good quality coffee they consumed. So the coffee had its own role in developing this language and good quality coffee was exported to the entire world from a place called Java Island. Hence they fixed the name og the place for the language as Java. And the symbol for Java language is coffee cup and saucer. By September of 1994, Naughton and Jonathan Payne started writing Web Runner-a Java-based Web browser, which was later renamed as Hot Java. By October 1994, Hot Java was stable and was demonstrated to Sun Executives. Hot Java was the browser, having the capabilities of executing applets, which are programs designed to run dynamically on internet. This time, Javas potential in the context of the World Wide Web was recognized. Sun formally announced Java and Hot Java at Sun World conference in 1995, soon after , Netscape Inc. announced that it would incorporate Java support in its browser Netscape Navigator. Later , Microsoft also announced that they would support Java in their Internet Explorer Web browser, further solidifying Javas role in the World Wide Web. On January 23rd 1996, JDK 1.0 version was released. Today more than 4 million developers use Java and more than 1.75 billion devices run Java. Thus, Java pervaded the world.
Features of Java:
Apart from being a system independent language, there are other reasons too for the immense popularity of this language. Let us have a look at some of its features. 1. 2. 3. 4. 5. 6. 7. 8. Simple Secure Portability Object-oriented Robust Multithreaded Architecture-neutral Interpreted
Page 4 of 38
Simple:
Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java. Also, some of the more confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner. Beyond its similarities with C/C++, Java has another attribute that makes it easy to learn: it makes an effort not to have surprising features. In Java, there are a small number of clearly defined ways to accomplish a given task.
Secure:
Security problems like eaves dropping, tampering, impersonation, and virus threats can be eliminated or minimized by using Java on internet.
Portability:
If a program yields the same result on every machine, then that program is called portable. Java programs are portable. This is the result of Javas system independence nature.
Object-Oriented:
Although influenced by its predecessors, Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike a balance between the purists everything is an object paradigm and the pragmatists stay out of my way model. The object model in Java is simple and easy to extend, while simple types, such as integers, are kept as high-performance non objects.
Robust:
The multi platform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. To gain reliability, Java restricts you in a few key areas, to force you to find your mistakes early in program development. At the same time, Java frees you from having to worry about many of the most common causes of programming errors. Because Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. In fact, many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in Java. Knowing that what you have written will behave in a predictable way under diverse conditions is a key feature of Java. To better understand how Java is robust, consider two of the main reasons
Page 5 of 38
for program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors). Memory management can be a difficult, tedious task in traditional programming environments. For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This sometimes leads to problems, because programmers will either forget to free memory that has been previously allocated or, worse, try to free some memory that another part of their code is still using. Java virtually eliminates these problems by managing memory allocation and de-allocation for you. (In fact, de-allocation is completely automatic, because Java provides garbage collection for unused objects.) Exceptional conditions in traditional environments often arise in situations such as division by zero or file not found, and they must be managed with clumsy and hard-to-read constructs. Java helps in this area by providing object-oriented exception handling. In a well-written Java program, all run-time errors can and should be managed by your program.
Multithreaded:
Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multi process synchronization that enables you to construct smoothly running interactive systems. Javas easy-to-use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem.
Architecture-Neutral:
A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorroweven on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was write once; run anywhere, any time, forever. To a great extent, this goal was accomplished.
Distributed:
Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak) included features for intra address-space messaging. This
Page 6 of 38
allowed objects on two different computers to execute procedures remotely. Java revived these interfaces in a package called Remote Method Invocation (RMI). This feature brings an unparalleled level of abstraction to client/server programming.
Dynamic:
Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of byte code may be dynamically updated on a running system.
Method Area
Heap
Java stacks
PC registers
Interpreter
JIT compiler
Execution Engine
Operating System
Fig. Architecture of Java Virtual Machine First of all, the java program is converted into a class file consisting of byte code instructions by the java compiler. Remember, this java compiler is outside the JVM. Now this .class file is given to the JVM, in JVM there is a module (or program) called loader sub system, which performs the following functions: It loads the .class file into memory.
Page 7 of 38
Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicious, the execution is rejected immediately. If the byte instructors are proper, then it allocates necessary memory to execute the program. This memory is divided into 5 parts, called run time data area, which contain the data and results while running the program. These areas are as follows:
Method area:
Method area is the memory block, which stores the class code, code og the variables, and code of the methods in the Java program. (Method means functions written in a class)
Heap:
This is the area where objects are created. Whenever JVM loads a class, a method and a heap area are immediately created in it.
Java stacks:
Method code is stored on Method area. But while running a method, it needs some more are memory to store the data and result s. this memory is allocated on Java stacks. So, Java stacks are memory areas where Java methods are executed.
Execution Engine:
Execution engine contain interpreter and JIT (Just in Time) compiler, which are responsible for converting the byte code instructions into machine code so that the processor will execute them. Most of the JVM implementations use both the interpreter and JIT compiler simultaneously to convert the byte code. This technique is also called adapative optimizer.
Parts of Java:
Sun Microsystems Inc. has divided into 3 parts1. Java Standard Edition (JSE) 2. Java Enterprise Edition (JEE) 3. Java Micro Edition (JME) Let us discuss them in brief here: Java SE: it is the Java Standard Edition that contains basic core Java classes. This edition is used to develop standard applets and applications.
Page 8 of 38
Java EE: it is the Java Enterprise Edition and it contains classes that are beyond Java SE. In fact, we need Java SE in order to use many of the classes in Java EE. Java EE mainly concentrates on providing business solutions on a network. Java ME: it stands for Java Micro Edition. Java ME is for developers who develop code for portable devices, such as a PDA a cellular phone. Code on these devices needs to be small in size should take less memory. Differences between C++ and Java: By the way, C++ is also an object-oriented programming language, just like Java. But there are some important feature-wise differences, between C++ and Java. Let us have glance at them in table
C++
It is not a purely object-oriented programming language, since it is possible to write its programs without using a class or an object. Pointers are available in it Allotted memory and deallocating memory is the responsibility of the programmer. It has goto statement. Automatic casting is available in it.
Java
It is purely an object-oriented programming language, since it is not possible to write its program without using at least one class. We cannot create and use pointers in it Allocation and deallocation of memory will be take care of by JVM. It does not have goto statement. In some cases, implicit casting is available. But it is advisable that the programmer should use casting whenever required. # define, type def and header are not available in Java, but there are means to achieve them. It supports 4 access specifiers in it private, public, protected and default. Only constructors are there in it. No destructors are available in it.
There are 3 access specifiers in it private, public, and protected. There are constructors and destructors in it.
Conclusion: We have learned the features of the Java and got familiar with the JVM architecture along with part of Java. By now, we must have got a glimpse of Java. Along with all this, we have also compared the C++ with Java.
Page 9 of 38
DATA TYPES
Page 10 of 38
Here we are declaring that x is a variable, which can store int (integer) type data. This means int is representing the nature of data to be stored into x. int is also called a data type. For example, x can store an integer number like 1235 as: x=1235; Here, x is a variable and = represents that the value 1235 is stored into x. This value 1235 stored into x is also called literal.
Data type
Byte Short Int Long
Memory size
1 byte 2 bytes 4 bytes 8 bytes
Data type
Float Double
Memory size
4 bytes 8 bytes
What is difference between float and double? Float can represent up to 7 digits accurately after decimal point, whereas double can represent up to 15 digits accurately after decimal point.
Page 11 of 38
Literals:
A literal represents a value that is stored into a variable directly in the program. These are as follows: 1. Integer literals 2. Float literals 3. Character literals 4. String literals 5. Boolean literals
Integer Literals:
It represent the fixed integer values like 100, -55, 123450, etc. All these numbers belong to decimal system, which uses 10 digits (from 0 to 9) to represent any number. Suppose, we want to write an integer in octal number system (octal number system uses 8 digits, from 0 to 7) then we should prefix 0 before the number. To represent hexadecimal number (hexadecimal number system uses 16 digits from 0 to 9 and from A to F). we should prefix 0x before the value. int decVal = 26; //the number 26,in decimal int octVal = 032; //the number 26, in octal int hexVal = 0x1a; //the number 26, in hexadecimal
Float Literals:
Float literals represent fractional numbers. These are the numbers with decimal points like 2.0, 0.005, 3.14, 6.1e-22, etc. which should be used with float or double type variables. While writing these literals, we can use E or e for scientific notation, F or f for float literal, and D or d for double literal (this is the default and generally omitted).
Page 12 of 38
double d1=123.4; double d2 =1.234e2; //same value as d1, but in scientific notation float f1 = 123.4f;
Character Literals:
Character literals indicate the following: General characters, like A, b, 9, etc. Special characters, like ?, @, etc. Unicode characters, like \u0042 (this represents a in ISO Latin 1 characters set). Escape sequence (backslash codes) like \n, \b, etc. Character literals should be enclosed in single quotation marks. The preceding Unicode characters and escape sequence can also be represented as strings.
String Literals:
It represent objects of string class. For example, Hello, Anil Kumar, AP1201, etc. will come under it which can be directly stored into a string object.
Boolean Literals:
It represent only two values-true and false. It means we can store either true or false into a Boolean type variable.
Conclusion:
To use the naming conventions, a programmer can avoid a lot of mistakes in writing the names of packages, classes, methods, variables, etc. This will improve readability as well as understandability of a program. So maintaining naming conventions is a good programming habit. A program generally acts on data, processes it, and provides the results. So data is very important element of a program.
Page 13 of 38
Page 14 of 38
properties vars Tom 1 foot Brown 5 years action methods run() bark() eat()
object.Tom
Fig. Class and object We can use a class as a model for creating objects. To write a class, we can write all the characteristics of objects which should follow the class. These characteristics will guide us to
Page 15 of 38
create the objects. A class and its objects are almost the same with difference that a class does not exist physically, while an object does.
Page 16 of 38
POLYMORPHISM
Page 17 of 38
POLYMORPHISM
It came from the Greek word, poly means many and morphism means forms. The ability to exist in different forms is called polymorphism. In java, a variable, an object or a method can exist in different forms, thus performing various tasks depending on the context. Because same variable or method can perform different tasks. The main advantage of it is to provide the flexibility. There are two types of polymorphism in java. 1. Static polymorphism (or) Compile time polymorphism (or) Early binding 2. Dynamic polymorphism (or) Runtime polymorphism (or) Dynamic binding
Static Polymorphism:
The polymorphism exhibited at compilation time is called static polymorphism. Here the java compiler knows without any ambiguity which method is called at time of compilation. Of course, JVM executes the method later, but the compiler knows and can bind the method call with method code (body) at the time of compilation. So, it is also called static binding or compile time polymorphism.
Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic polymorphism.
Note: non private, non static, non final methods will be recognized at run time by the JVM just
before executing the respective class constructor. These method overloading is an example for dynamic polymorphism due to the above reason.
Method Overriding
Writing two or more methods with the same name and same signatures is called method overriding. It is done in super and sub classes, In it, method return types should also be same.
JVM decides which method is called depending on the data type (class) of the object used to call the method. It is done when the programmer wants to provide a different implementation (body) for the same feature. It is code refinement. Same method is refined It is code replacement. The sub class method to perform a different task. overrides (replaces) the super class method.
Page 18 of 38
Conclusion:
If the same variable or method or an object perform different tasks, it is said to exhibit polymorphism. In this chapter, we have seen how variables and methods can exhibit polymorphism. A programmer goes for method overriding when he wants to extend the available features of the class. A programmer does method overriding when he wants to extend the perform a different task with the same method. Even the objects can also change their form at runtime and can perform different tasks depending on how they are referenced. This is possible by casting the object types.
Page 19 of 38
STATIC KEYWORD
Page 20 of 38
STATIC KEYWORD
Static is java keyword it is utilized for static variables, static methods, static blocks and static inner classes but not for the outer class.
Static Variables:
It could be recognized & executed at the time of loading the byte code of respective class. The value of a variable is not varied for object to object then we should declare that variable as static. In java applications static variables will be accessed by either by using class name directly (or) by using respective class object reference variable. Ex: Class A { int x=10; static int y=20; public static void main(String[] args) { //System.out.println(A.x);//compile time error System.out.println(A.y); A a=new A(); System.out.println(a.y); System.out.println(a.x); } }
Static Methods:
It is a java method, which will be recognized at the time of loading respective class byte code & whose execution is completely depending on the movement when we access the method. It will allow directly static variables of the same class and which will not allow non static variables directly. If we want use non static variables in static method then we have to create the respective
Page 21 of 38
class object with the generated reference variable only in java applications we are able to access static methods either by using class name directly (or) by using the respective class object reference.
Static Block:
It is java feature, which will be recognized & executed at the time of loading the respective class byte code. Static blocks will allow static variables directly, it will not allow non static variables. Syntax: static{ ----------}
Static-Flow control:
If we provide static variables, static blocks with in a single class then they will be executed at the time of loading byte code as per the order in which we provide.
Page 22 of 38
INHERITANCE
Page 23 of 38
INHERITANCE
It is concept where a new classes can be produced from existing classes. The newly created class acquires all the features of existing class from where it is derived. For example, Class Teacher { int id; String name; String address; float sal; void setId(int id) { This.id = id; } int getid() { return id; } Void setName(String name) { this.name=name; } String getName() { return name; } void setAddress(String address)
Page 24 of 38
{ this.address=address; } String getAddress() { return address; } void setSal(float sal) { this.sal=sal; } float getSal() { return sal; } } If another programmer want inherits the Teacher class then he/she should write class Student extends Teacher
Advantage of inheritance:
A programmer reuses the super class code without rewriting it, in creation of sub classes so, developing the classes becomes very easy. Hence the programmers productivity is increased.
super keyword:
If we create an object to super class, we can access only the super class members, but not the sub class members. But if we create sub class object, all the members of both super and sub classes are available to it. This is the reason, we always create an object to sub class in inheritance. Sometimes the super class members and sub class members may have same names. In the case by default only sub class member are accessible.
Page 25 of 38
super can be used to refer to super class variables, as: super.variable_name super can be used to refer to super class constructor. We need not call the default constructor of the super class, as it is by default available to sub class. To call the parameterized constructor, we can write: super(values);
Protected Specifier:
The private members of the super class are not available to sub classes directly. But sometimes, there may be a need to access the data of super class to make the members of the super class available directly in its sub classes.
Page 26 of 38
INTERFACES
Page 27 of 38
INTERFACES
An interface contains methods which are all abstract and hence none of the methods will have body. Only method prototypes will be written in the in the in interface. So an interface can be defined as a specification of method protocol. Since, we write only abstract methods in the interface, there is possibility for providing different implementations (body) for those abstract methods depending on the requirements objects.
Interface:
An interface contains only abstract methods which are all incomplete methods. So it is not possible to create an object to an interface. In this case, we can create separate classes where we can implementation classes. Since, implementation classes will have all the methods with body, it is possible to create objects to the implementation classes. The flexibility lies in the fact that every implementation class can have its own implementation of the abstract method of the interface.
Abstract methods
interface
implementation class1
implementation class 2
object of class 1
object of class 2
Fig. interface and its implementation classes By default the interface methods are public and abstract. Hence interface contains only the abstract methods and by default interface variables are public static final.
NOTE: No, we cant implementing an interface means writing body for the methods. This
cannot be done again in an interface, since none of the methods of the interface can have body. It is possible to write a class with in an interface.
Page 28 of 38
Abstract class
It is written when there are some common features shared by all the objects. When it is written, it is the duty of the programmer to provide sub classes to it. It contains some abstract methods and some concrete method. It can contain instance variables also. All the abstract methods of the abstract class should be implemented in its sub classes. It is declared by using the keyword abstract.
Interface
It is written when all the features are implemented differently in different objects. It is written when the programmer wants to leave the implementation to third party vendors. It contains only abstract methods. It cannot contain instance variables. It contains only constants. All the (abstract) methods of the interface should be implemented in its implementation classes. It is declared using the keyword interface.
Abstract method: It is a method without method body. It is written when the same method has
to perform different tasks depending on the object calling it.
Page 29 of 38
MULTITHREADING
Page 30 of 38
MULTITHREADING
Before know about multithreading, we should know what necessitated multithreading. For that, we need to know about multitasking.
Multitasking:
The concept of executing multiple functionalities simultaneously is known as multitasking.
To set a new name to a thread: t.setName(new name); To get the priority of a thread: int priority_no= t.getpriority(); To set the priority of a thread: t.setpriority (int priority_no); To test if a thread is still alive: t.isAlive() returns true/false To know the number of threads actively running in a thread group: tg.activeCount();
Thread lifecycle:
Starting from the birth of a thread, till its death, a thread exists in different states which are collectively called Thread Life Cycle. A thread will be born when it is created using Thread class as: Thread t=new Thread();
Applications of threads:
In a network, a server has to render its services to several clients at a time. So, by using threads at server side programs, we can make the threads serve several clients at a time. Another application of threads is animation, where an object, an image or some text is moved from one place to another on the screen.
Page 32 of 38
SCANNER
Page 33 of 38
SCANNER
The main use of java.util.Scanner is to read values from System.in or a file. Many Scanner methods fit a simple pattern.nextXYZ() scans and returns a value of type XYZ.hasnextXYZ() returns true if something of type XYZ is available to be read next. Additional types. The summary below just shows methods for ints and doubles because these are most common, but scanner also supports BigDecimal, BigInterger, Float (returns float), Boolean (returns Boolean), Long (returns long), Short (returns short), and Byte (returns byte). The XYZ in the prototypes below stands of for one of these additional types.
Scanner methods Assume: int i, double d, String s, Boolean b, Scanner sc and x stands for a type that should be
clear from context.
Constructors:
sc=new Scanner(System.in); Creates a Scanner which reads from System.in. sc=new Scanner(s); Create a Scanner which reads from String s.
JDBC
Page 35 of 38
Page 36 of 38
JDBC History:
The JDBC API is a mature technology, having first been specified in January 1997. In its initial release, the JDBC API focused on providing a basic call-level interface to SQL databases. The JDBC 2.1 specification then broadened the scope of the API to include support for more advanced applications and for the features required by application servers to manage use of the JDBC API on behalf of their applications. The JDBC 3.0 specification operated with the stated goal to round out the API by filling in smaller areas of missing functionality. With JDBC 4.0, our goals are twofold: Improve the Easeof-Development experience for all developers working with SQL in the Java platform. Secondly, provide a range of enterprise level features to expose JDBC to a richer set of tools and APIs to manage JDBC resources.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access. Two-tier Architecture:Java Applications Client Machine JDBC DBMS proprietary protocol
DBMS
Database server
In the two-tier model, a java application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A users commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the users machine as the client, and the machine housing the data source as the server. The network can be an internet, which, for example, connects employees within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a middle tier of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
In the above two architectures The Java Application Program communicates with JDBC. The JDBC contains: JDBC API, JDBC Driver Manager, and JDBC driver. JDBC API contains java.sql package, javax.sql packages. JDBC Driver Manager is class defined in JDBC API. JDBC driver is software that communicates with Data base server.
Page 38 of 38