Sei sulla pagina 1di 24

BSc IInd Year

UNIT - I

JAVA UNIT - I
Basic Concepts of OOP
Object oriented is a term which is interpreted differently by different people. It is therefore necessary to understand some of the concepts extensively in object oriented programming (OOP). It is an approach to program organization and development which attempts to eliminate some of the convectional programming methods by incorporating the best of structured programming features with several new concepts. Object Oriented Programming is an approach that provides a way of modularizing programs by creating portioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Object Oriented Programming organizes a program, around its data i.e; object and set of well defined interfaces to that data and object oriented program can be characterized as data controlling access to code. The basic concepts of OOP are 1. OBJECT :Objects are the basic run time entries in an object oriented system. They may be representing a person, a place, a table etc The objects are two types. They are 1. Real life objects 2. Software objects The real life objects are physically existed so that they have look and feel. The real life objects share two characteristics. They all have state and behaviour. For eg: - Dogs have state (name, colour etc) and behaviour (barking, fetching, wagging tail etc) The software objects are created on the RAM Memory, which does not have any look and feel. In real life Objects any action is performed with the help of state only, the state is nothing but the properties of the object or characteristics of the object. Behaviour representing different actions. The behaviour is depending on the state of object. 2. CLASS :A Class mechanism encapsulating state and behaviour. A class mechanism encapsulate the state and behaviour as a single unit. In programming languages variables are represent the state and functions are representing as the behaviour. An OOPs with JAVA and Data Structure Page No: 1

BSc IInd Year

UNIT - I

Object Oriented any state cannot be changed directly the state can be changed with the help of operations or functions only. Representation of Object in a Class:-

3. METHODS :In C Language it is called as functions, in C++ it is called as Member functions and in Java called as Methods. The Methods always associates with the class and can be defined inside the class only. 4. ABSTRACTION AND ENCAPSULATION :The Wrapping of data and Methods into a single unit is known as Encapsulation. Data Encapsulation is the most striking feature of a class. The Data is not accessible to the outside world and only these methods which are wrapped in the class can access it. These methods provide the interface between the objects data and the program. This insulation of data from direct access by the program is called data hiding. Abstraction refers to the act of representation essential features without including background details and explanations. The Abstraction may be classified into two types. They are : 1. Data Abstraction 2. Function Abstraction 5. INHERITANCE :Inheritance is the process by which objects of one class acquire the properties of another class. Inheritance supports the concepts of hireachical classification. In OOP the concept of inheritance provides the idea of reusability. This means that we can add additional feature to an existing class without modifying it. 6. POLYMORPHISM :Polymorphism is another important OOP concept. It means the ability to take more than one form. The Behaviour depends upon the types of data used in the operation. OOPs with JAVA and Data Structure Page No: 2

BSc IInd Year

UNIT - I

For eg: - An Operation may execute different behaviour in different instances. The below diagram shows Polymorphism

7. Dynamic Binding :Binding refers to the linking of the procedure call to the code to be executed in response to the call. Dynamic Binding means that the code associated with a given procedure is not known until the time of call at a run time. BENEFITS OF OOPS:Object Oriented contributes to the solution of many problems associated with the development and quality of software products. The principle advantages are:1. Through inheritance we can eliminate redundant code and extend the use of existing classes. 2. Data hiding helps the programmer to construct secured programs. 3. Software Complexity can be easily managed. 4. It is easy to partition the work in a project based on objects. 5. It is possible to have multiple objects to coexist without any interference. 6. It is possible to map objects in the problem domain to those objects in the program. 7. Object oriented systems can be easily upgraded from small to large systems. APPLICATIONS OF OOP:OOP is the programming buzz words today. Applications of OOP are beginning to gain importance in many areas. The most popular application of OOP is Windows. 1. Real time Systems 2. Object oriented databases 3. Hyper text, Hyper media and expert text 4. AI and expert systems 5. Simmulation and modeling OOPs with JAVA and Data Structure Page No: 3

BSc IInd Year 6. Decision support and office alto machine systems 7. Network and parallel programming 8. CIM, CAD, CAM Systems. OBJECT ORIENTED PARADIGM:-

UNIT - I

The major Objective of Object Oriented approach is to eliminate some of the flows encountered in the procedural approach, OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. OOP allows us to decompose a problem into a number of entries called Objects and then bulled data and functions around these entities. The below figure shows data and methods

Object = data+method The data of an object can be accessed only by methods associated with that object. Some of the features of Object oriented paradigm are 1. 2. 3. 4. 5. 6. Emphasis is on data rather than procedure Programs are divided into what are known as objects Objects may communicate with each other through methods. Now data methods can be easily added whenever necessary. Follows bottom of approach in program design. Data is hidden and cannot be accessed by external functions.

HISTORY OF JAVA:Java is a General purpose Object Oriented programming language. Developed by Sun micro system (Stanford university Network), in 1992. Originally called OAK by James gosling and his team members Green is the name of the project to develop a device. The goal of the language is make it simple, portable and highly reliable. JAVA is an increment Version of C and C++. The current computer version of JAVA was released in 23rd may 1995.

OOPs with JAVA and Data Structure

Page No: 4

BSc IInd Year

UNIT - I

Year

Version

Packages and Classes

Code Name --

Features Being a new software, all are new features. Initially JAVA was supported by Net scap Navigator. Later it is supported to the Internet Explorer. In this Version the event handling is improved, inner classes are introduced. From this Version only the real power of JAVA is getting started. In this version collection of frame work (JAVA, Util), Swings, JVM Performance is improved. In this Version hot-spot JVM introduced for completion of interpretation as early as Possible. This is very popular version among all JAVA versions, in this Version (NIO), Logging such topics are introduced. In this version people are concentrated on reducing the code size. The new features ENUM, Boxing and etc.

23rd May 1.0 Version 8 Packages 1995 22 Classes

9th Feb 1997 8th Dec 1999

JDK 1.1

23 Packages 504 Classes -Playground

JDK 1.2(or) 59 packages J2SDK 1.2 1520 Classes

8th May 2000 6th Feb 2002

JDK 1.3(or) 76 Packages J2SDK 1.3 1842 Classes

Kestrol

JDK 1.4(or) 135 Packages J2SDK 1.4 2991 Classes

Merlin

30th Sep JDK 1.5(or) 165 Packages 2004 J2SE 5.0 Over 3000 Classes unboxing

Tiger

OOPs with JAVA and Data Structure

Page No: 5

BSc IInd Year

UNIT - I

JAVA FEATURES OR BUZZ WORDS:Sun micro systems officially describe Java with the following features. 1. Compiled and Interpreted:Usually a computer language is either compiled or interpreted. Java continues both these approaches thus making Java a two stage system. First, Java compiler translates source code into Byte code instructions and therefore, in the second stage Java interpreter generates machine code using byte code. 2. Platform independent and portable:Java programs can be easily moved from one computer to another which means Write Once Run anywhere (WORA). This approach is possible using Byte code. 3. Simple:Java was designed to be easy for professional programmers to learn and use affectively. Java inherit syntaxes from C language and object oriented features of C++. 4. Secure:When we use Java on the internet wee can safely download web applications without any viral infection (virus). This is possible by providing firewalls between a network applications and your computer. 5. Object Oriented:Java is object oriented language. The object mode in Java is simple and easy to extend, while simple types are kept as high performance non-objects. 6. Robust:Java is a robust language. It provides many safeguards to ensume reliable code. It has strict compile time and runtime checking for data types. Java incorporates the concept of exception handling which captures series errors and eliminates any risk of crashing the system. 7. Distributed:OOPs with JAVA and Data Structure

Page No: 6

BSc IInd Year

UNIT - I

Java is designed the distributed environment of internet because it handles TCP/IP (Transmission control protocal and Internet protocal) protocalls. The original version of Java (OAK) included features for intra address space. This allowed objects on two different computers to execute. Java also has remote method innovations (RMI). 8. Multi Threaded:Java was designed to meet the real world requirement of creating interactive network programs to accomplish, this Java supports multi threaded program which allows implementing the program and executing parallely. 9. Dynamic:Java programs carry with libraries, methods and objects at run time. Java programs support functions return in other language such as C and C++ these functions are known as Native methods. This facility enables the programmers to use the efficient functions available in these languages. Native methods are linked dynamically at runtime. 10. High Performance:Java performance is impressive for an interpreted language, mainly due to the use of intermediate byte code, java was designed to perform well on very low power CPU. Java Byte code was carefully designed so that it would be easy to translate into machine code by using just in time IT) compiler. DIFFERENCES BETWEEN C AND JAVA:Java is a lot like C but the major difference between Java and C is that Java is an object oriented language. The following are the major differences between Java and C. 1. Java does not include the C unique statement keywords size of(), typedef. 2. Java does not contain the data type struct and union. 3. Java does not define the type modifier keywords. auto, extern, register, signed, unsigned. 4. Java does not support an explicit pointer type. 5. Java does not have preprocessor (#define, #include) 6. Java requires that the functions with no arguments must be declared with empty paranthesis and not with the void keyword as alone in C. 7. Java adds new operators such as instance of and >>>. 8. Java adds labeled break and continue statements. 9. Java has many features required for OOP. DIFFERENCES BETWEEN JAVA AND C++:Java is a true object oriented language while C++ is basically C with object oriented extension. The below are some major differences. 1. Java does not support operator overloading. 2. Java does not have template classes as in C++. 3. Java does not support multiple inheritances of classes. OOPs with JAVA and Data Structure Page No: 7

BSc IInd Year 4. 5. 6. 7. Java does not support global variables. Java does not use pointers. Java has replaced distructor with a finalize function. There are no header files in Java.

UNIT - I

Overlapping of C,C++, and Java JAVA AND INTERNET:Java is strongly associated with internet because of the fact that the first application program in Java was hot-Java, A web browser to run applets on internet. Internet users can use Java to create applet programs and run then using a java enabled browser. Such as Hot Java. They can also use a Java-Enabled browser to download on applet located on a computer anywhere in the internet and run it on his local computer. The below figure shows downloading an applet from the internet.

JAVA AND WORLD WIDE WEB:World Wide Web (www) is an open ended information retrieval system designed to be used in the Internet distributed environment. This system contains what are known as web pages that provide both information and controls. The web system is an openended and we can navigate to a new document in any direction. This is made possible with the help of a language called Hyper text markup language(HTML) The below figure shows web structures. OOPs with JAVA and Data Structure Page No: 8

BSc IInd Year

UNIT - I

Java communicates with a web page through a special tag called <APPLET>. The following are the communications steps. 1. The user sends a request for an HTML document to the remote computers web server. 2. The HTML document is returned to user browser after completion of accept request, process the request and giving the response. 3. The corresponding applet byte code is transferred to the users computer. 4. The java enabled browser on the users computer interprets the byte code and provides the output. 5. The user may have further interaction with the applet. The below figure shows Javas interaction with the web.

JAVA ENVIRONMENT:Java environment includes a large number of development tools and hundreds of classes and methods. The development tools are the part of system known as Java development kit(JDK) and the classes and methods are part of java Standard Library(JSL),also known as the Application programming interface(API) OOPs with JAVA and Data Structure Page No: 9

BSc IInd Year

UNIT - I

JAVA DEVELOPMENT KIT:The Java development kit comes with a collection of tools that are used for the developing and running java programs. They include

TOOLS i) Applet viewer ii) Java iii) Javac iv)Javadoc v) Javah vi) Javap vii) Jdb

DESCRIPTION enables us to run java applet. (Without actually using a java browser) java interpreter, which runs applets and applications by reading and interpreting bytecode files. The java compiler, which translates java source code to bytecode files that the interpreter can understand. creates HTML format documentation from java source code files. produces header files for use with native methods. java dissembler which enables us to convert bytecode files into program. java debugger which helps us to find errors in our programs.

APPLICATION PROGRAM INTERFACE (API):Java standard library (JSL) includes hundreds of classes and methods grouped into several functional packages. Most commonly used packages are i) Languages support package : A collection of classes and methods required for implementing basic features of Java. ii) Utilities package : A collection of classes to provide utility function such as date and time functions. iii) Input/output package : A collection of classes required for input/output manipulations. iv) Networking package : A collection of classes for communicating with other packages via- internet. v) AWT package : The abstract window tool kit contain classes that implements platform independent graphical user interface GUI. vi) Applet package : This includes set of classes that allows to create java applets. The below figure shows the process of building and running java application programs.

OOPs with JAVA and Data Structure

Page No: 10

BSc IInd Year

UNIT - I

HARDWARE AND SOFTWARE REQUIREMENTS: Java is currently supported on windows 95,wiondows NT, windows XP,sun solarrays,macintosh and unix machines. The minimum hardware and software requirements to install the java as follows. i) JVM 486 system. ii) Minimum of 8 MB memory. iii) Windows software. iv) Hard drive. v) A CD-RAM drive. vi) Mouse. OVERVIEW OF JAVA:Java is a general purpose OOP language. We can develop two types of Java programs. i) Stand-alone applications. ii) Web applications (or) Web Applets. Stand alone applications are program written in Java to carry out certain tasks on a stand alone local computer. Executing a stand-alone java program involve two steps. 1. Compiling source code into byte code Javac compiler 2. Executing the bytecode program using Java interpreter. Applets are small Java programs developed for internet applications. An applet located in a distant computer (server) can be downloaded via internet and execute on local computer using a Java capable browser. The below figure shows the two ways of using Java

OOPs with JAVA and Data Structure

Page No: 11

BSc IInd Year

UNIT - I

Simple Java Program:Class Praveen { Public static void main (String args[]) { System.out.println (Hai I am Praveen); } } Class Declaration:The first line Class Praveen Declares a class, which is object oriented construct. Java is a true object oriented programming language so everything must be placed inside the class only class is a key word and declares that a new class definition follows class name like (Praveen) Is a java identifier specifies the name of the class to be defined. Opening and Closing braces:Every class definition in Java begins with opening and closing with matching brase The main line:1. Public static void main (String args[]) defines a method named main. 2. Every Java application program must include the main method. This is similar to main function in C/C++. 3. This is a starting point for interpreter to begin the execution of the program. 4. A Java application can have any number of classes but only one of them must include a main method. OOPs with JAVA and Data Structure Page No: 12

BSc IInd Year Note: - Java applets will not use the main method.

UNIT - I

Public: - The keyword Public is an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes. Static: - The keyword static is to declare this method as one that belongs to the entire class and not part of the any objects of the class. The main must always be declared as static because the interpreter uses this method any objects are created. (access modifier). Void: The type modifier voids states that the main method does not return any value. The Output line:System.Out.Println:- It is similar to the printf() statement of C or Cout<< construct of C++. The println method is a member of the out object, which is a static data member of system class. Note: - Every Java statement ends with (;) semi column. Java program structure:A Java program may contain many classes of which only one class defines a main method. Classes contain data members and method that operate on the data members of the class. Methods may contain datatype declarations and executable statements. The General structure of a Java program.

Documentation Section:-

OOPs with JAVA and Data Structure

Page No: 13

BSc IInd Year

UNIT - I

The Documentation section comprises a set of comment lines giving the name of the program, the author and other details. The comments must explains why and what of classes and how of algorithms. Package Statement:The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. Import Statements:This statement instructs the interpreter to load the class contained in the package. For eg: - import java.lang.Math; Interface Statements:An Interface is like a class but include a group of method declarations. This is also an optional statement and is used only when we wish to implement multiple inheritance feature in the program. Class Definition:A java program may contain multiple class definitions classes are the primary and essential elements of a Java program. The number of classes used depends on the complexity of the problem. Main Method class:Since every Java stand- alone program requires a main method as its starting point, this class is the essential part of a Java program

Java Tokens:The token is nothing but the smallest individual unit of a statement or the smallest thing of a program. The Java language can be supported the following tokens.] 1. White Space: Java is a free- formed language, this means that we do not need to follow any special rules in java white space is possible with Space bar, tab, or new line. 2. Identifier: - Identifiers are used to identify a particular element, those are including like variable name, function name, class name pr object name. 3. Comments: - A comment is a statement which explains the purpose of the program. Java can support three types if comments. Single line comments are declared as [//]. Multi line or paragraph comments identifies as [/*--------*/]. HTML format declared as [/*----*----*----OOPs with JAVA and Data Structure Page No: 14

BSc IInd Year *------*/]

UNIT - I

4. Literals: - A literal is a value representation. A constant value in Java is created by a literal. For eg: - 10, 10.2,a.abc. 5. Key words: - All keywords are pre defined words, it means that the word meaning is already being explained to the compiler. There are 48 types of keywords supported by Java. They are Abstract char double for int return this boolean class else goto interface shork throw break const extends if long static throws byte continue final implements private strictfp try case default finally import protect super void catch do float instanceof public switch volatile white synchronized transient native new package 6. Operators:- Java provides rich operator environment. An operator is a symbol which can do the operation between the operands. The operand can be characterized in three categories. They are 1. Unary Operators 2. Binary Operators 3. Ternary Operators 7. Separators: - In Java there are a few characters that are used as separators. The most common used separator is semi column (;). For eg: - <, >, {, }, (, )..etc.

Datatypes: The datatypes are used to store the type of values in the memory location that means what type of the data the user is going to store in the memory locations. Java supporting the following datatypes.

OOPs with JAVA and Data Structure

Page No: 15

BSc IInd Year

UNIT - I

Java defines 8 simple types of data they are byte, short, int, long, float, double, char, boolean. These can be put in the four groups they are Integer: - It includes byte, short, int and long. All of these are sign positive and integral values. Java does not support unsigned positive only integers. The ranges and width of the integers as shown in the below table. Name Long Int Short Byte Floating point types:Floating point numbers are also known as real numbers are used when evaluating expressions that require fractional precision. Name width Range
-38 38

width 64 bits 32 bits 16 bits 08 bits

range 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 2,147,483,648 to 2,147,483,648 32,768 to 32,767 128 to 127

Float

32 bits

3.4e

to 3.4 e
-308 308

OOPs with JAVA and Data Structure

Page No: 16

BSc IInd Year double 64 bits 1.7 e

UNIT - I to 1.7e

Characters:In order to store character constants in memory, Java provides a character datatpe called Char. This type assumes a size of two bytes but basically it can hold only a single character. Range 0 to 65536 Boolean type:Java has a simple type called boolean for logical value, it can have only one of two possible values true or false, This is a type returned by all relational operators such as : a<b. Boolean is also the type required by the conditional expressions. That governs the control statements such as if and for. Java Statements:The statements in Java are like sentence in natural languages. A statement is an executable combination of tokens ending with a (;) semicolumn mark. Statements are usually executed in sequence in the order in which they appear. The below table shows summary of Java statements. Statement Description 1. Empty Statement 2. Labeled Statement These do nothing and are used during program development as a place holder. Any Statement may begin with label. Such Labels must not be keywords, already declared Local variables or previously used variables in the module. Most statements are expression statements. Java has seven types of expressions. They are assignments, pre and post increment or Decrement, method call and allocation expression. These select one of several control flows. These are if, ifelse, switch. These specify how and when looping will take place. These are while, do while, for. Jump statements pass control to the Or end of the current block or to a labeled Statement. Such as throw, break, continue, And return. These are used for handling issues with multi threading. These are used for safe handling of code That may cause exceptions like try, catch and finally. Page No: 17

3. Expression Statement

4. Selection Statement 5. Iteration Statement

6. Jump Statement beginning

7. Synchronization statements 8. Guarding Statement

OOPs with JAVA and Data Structure

BSc IInd Year

UNIT - I

Implementing Java Program:Implementing of Java application program involves a series of steps. They include 1. Creating the program 2. Compiling the program 3. Running the program Creating the program:We can create a program using a text editor. Assume that we have entered a following program. Class test { Public static void main (string[] args) { System.out.println(Hello world!); } } We must have to save the file called test.Java. This file is called the source file. Note that all Java source file will have the extension Java. Note also that if a program contains multiple classes, the file name must be the class name of the class containing the main method.

OOPs with JAVA and Data Structure

Page No: 18

BSc IInd Year

UNIT - I

Compiling the program:To compile the Java program you must run the Java compiler Javac, with the name of the source file on the command line as shown below. Javac test.Java. The compiler creates a file called class file containing the byte codes of the program. The compiler automatically names the bytecode with name like test.class. Running the program:We need to use the Java interpreter to run a stand-alone program. At the command prompt type Java test. Now the interpreter looks for the main method in the program and begins expressions from there. The compiler converts source code file into byte code files. These codes are machine independent and therefore can be run on any machine. The java interpreter reads the bytecode files and translates them into machine code for the specific machine on which the Java program is running. The below figure shows implementation of Java program.

JVM (Java virtual machine):All language computers translate source code into machine code for a specific computer. Java compiler produces an intermediate code known as bytecode for a machine that does not exist. This machine is called the Java virtual machine and it exists only inside the memory. It is a simulated computer within the computer and does all major functions of a real computer. The virtual machine code is not machine OOPs with JAVA and Data Structure Page No: 19

BSc IInd Year

UNIT - I

specific. The machine specific code id\s generated by the Java interpreter by acting as an intermediate between the virtual machine and the real machine.

The Java object framer work (API) acts as the interpreting between the user programs and the virtual machine which in terms acts as the interpreter between the operating system and Java object frame work. The below figure explains the layer of interpreter for Java programs.

Variable: - The variable is a basic unit of storage in a Java program. A variable is an identifier that denotes a storage location used to store data value. A variable is defined by the combination of an identifier.

Declaration of a variable: - In Java all variables must be declared before they can be used. The declaration does three things. 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration decides the scope of the variable. OOPs with JAVA and Data Structure Page No: 20

BSc IInd Year The basic form of a variable declaration is as follows type Identifier [=value] [,identifier] [,=value].etc. The type is one of primary datatypes or reference datatypes.

UNIT - I

The identifier is the name of the variable. We can initialize the variable by specifying an equal sign, the value. To declare more than one variable of that type use a (,0 separated list. For eg: - int a=1,b=2; float avg,res; char a=ch,b=c; byte a1,a2,a3; double avg; The variables which are having any one of the primary datatypes as prefix are called primitive variables. A variable which is having other than primary datatypes as prefix are called nonprimitive datatypes. For eg: - string s;

Scope and lifetime of variables: A block begins with an opening curlybrase and ended by a closing curlybrase. A block defines a scope, thus each time we start a new block we are creating a new scope. Variables declared and used inside methods are not available for used outside the method definition. These type of variables are called local variables.

Command line arguments: There may be occasions when we may like our program to act in a particular way depending on the input provided at the time of execution. This is achieved I Java programs by using what are known as command line arguments. OOPs with JAVA and Data Structure Page No: 21

BSc IInd Year

UNIT - I

We can write Java programs that can receive and use the arguments provided in the command line. Recall the signature of the main method used in our earlier programs. public static void main(string args[]) As pointed out earlier, args is declared as an array of strings(known as string objects). Any arguments provided in the command line(at the time of execution) are passed to the array args as its elements. We can simply access the array elements and use them in the programs we wish. For eg: - consider the command line java test Basic Fortran C++ Java This command line consists of four arguments . These are assigned to the arrays args as follows; Basic ---- args[0] Fortran ----args[1] C++-----args[2] Java----args[3]

Constants:Constants in Java refer to fixed values that do not change during the execution of program. Java supports several types of constants as follows Integer constants: An integer constant refers to a sequence of digits. There are three types of integers namely, 1. Decimal integer 2. Octal integer 3. Hexa decimal integer Decimal integer consist of a set of digit, 0 through 9, preceeded by an optional (--) sign. Eg: - Of decimal integer constants are 123---321 0 654321

Real constants: Integer numbers are inadequate to represent quantities that vary continuously such as distances, heights, temperature, prices and so on. These quantities are represented by numbers containing fractional parts like 9.999. Such numbers are called real(or floating point) constants. OOPs with JAVA and Data Structure Page No: 22

BSc IInd Year Eg of Real Constants: 0.0083 Single character Constants: --0.75 4.35 --36

UNIT - I

A single character constants (or) simply character constants contains a single character enclosed within a pair of single quote marks. Eg of character constants are: 5 x ; ,. String Constants: A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Eg: - Hello Java, 1991, Welldone. Back slash character constants: Java supports some special backslash character constants that are used in output methods. These characters combinations are known as escape sequences. Back slash character constants: Constant \b \f \n \r \t \ / \\ Meaning backspace formfeed newline carriage return horizontal tab single quote double quote Back slash

Type conversion and casting:If you have previous programming experience, if the two types are compatable then Java will perform the conversion automatically. For eg: - It is always possible to sign an int value to a long variable. How ever not all types are compatable and thus not all type conversions are implicitly allowed for insistence. There is no conversion defined from double to byte. Fortunately it still possible to obtain a conversion between incompatable types to do so we must use a caste which performs an explicit conversion between incompatible types.

Java at automatic conversion: When one type of data is assigned to another type of variable an automatic type conversion will take place if the following two conditions are met. 1. The two types are compatable. 2. The distinction type is larger than the scare type. When these two conditions are met a widening conversion takes place. For eg: - The int type is always large enough to hold all void byte values so know explicit vast statement is required.

OOPs with JAVA and Data Structure

Page No: 23

BSc IInd Year

UNIT - I

Casting incompatable type: To create a conversion between two incompatable types we must have a cast. A cast is simply an explicit type conversion if as this general form (target type) value here target types specify desired type. Convert the specified value to byte: Eg: int a; byte b; //.. b=byte(a); eg: - // demonstrate caste

OOPs with JAVA and Data Structure

Page No: 24

Potrebbero piacerti anche