Core Java Index

Embed Size (px)

Citation preview

  • 8/14/2019 Core Java Index

    1/46

    Core JavaINDEX

    1. Introduction to JAVA

    HistoryFeaturesJava Components

    JDKJVMByte codeJava and Internet

    Object Oriented programming principlesTypes of java programs

    2. Java Programming Features

    Variable and Variable declaration rules.KeywordsIdentifierTokenLiteralsCharacter setData typesArrayCommand Line ParametersOperators and types

    Conditional statementsLooping statementsBreak and continue statementsOctal and Hexadecimal nos in java

    3. Classes and Objects

    Class basics and structure of classObject and object initializationAccess specifiers or modifiersthis keywordGarbage Collection

    Method OverloadingConstructor

    Need of constructorParameterized constructor and constructor overloading

    Nested and inner classesPassing objects as a parameters to the constructor and methodsStatic member and methods

    4. Inheritance

    Inheritance basicsTypes of inheritance

    Super keywordfinalize method

  • 8/14/2019 Core Java Index

    2/46

    Dynamic method dispatchfinal keywordMultilevel inheritanceAbstract method and classInterface

    5. Wrapper Classes

    Number classByte classShort classInteger classLong classFloat classDouble classBoolean classCharacter classArrays classVector classString class

    6. Exception Handling

    Exception BasicsException class HierarchyCommon Exception classestry----catch----finally constructthrow and throws keywords

    user defined Exceptions7. MultithreadingThread basicsAdvantages of multithreadingThread prioritiesMain threadThread classThread life cycleThread class methodsCreating our own threads

    Runnable interfaceThread SynchronizationThread Interprocess Communication

    8. Applet Basics

    Applet and InternetApplication Vs AppletApplet class and methodsApplet life cycleHTML tagPassing parameters to the Applet

    getDocumentBase() and getCodeBase() methods

  • 8/14/2019 Core Java Index

    3/46

    9. Awt and Event Handling

    Awt Basics

    Awt Containers

    Panel and FrameAwt Componenets

    Label, TextField, TextArea, Button, List, Choice,Scrollbar, Checkbox and Radio ButtonsAwt Graphics classes

    Font, Graphics and Color classesLayout Managers

    FlowLayout, BorderLayout, GridLayout, CardLayoutMenu bar and Menu

    Event Handling

    Event classes

    ActionEvent, ItemEvent, AdjustmentEvent,WindowEvent, FocusEvent, MouseEvent,MouseWheelEvent, ContainerEvent, ComponentEvent

    Listeners

    ActionListener, ItemListener, AdjustmentListener,WindowListener, FocusListener, MouseListener,

    MouseWheelListener, ContainerListener, ComponentListener

    Anonymous inner classesAdapter classes

    10. File Input Output in JavaFile ClassRandomAccessFile ClassFileNameFilter Interface

    Stream

    Types Of streams

    Byte streams

    InputStream FileInputStream, ByteArrayInputStream,BufferedInputStream, DataInputStream

    OutputStream

    FileOutputStreamByteArrayOutputStreamBufferedOutputStreamDataOutputStreamPrintStream

    CharacterStreams

    Reader

    FileReaderInputStreamReaderBufferedReader

    CharArrayReaderPushBackReader

  • 8/14/2019 Core Java Index

    4/46

    Writer

    FileWriterCharArrayWriterBufferedWriterSerialization and Deserialization

    ObjectInputStream and ObjectOutputStream classes

  • 8/14/2019 Core Java Index

    5/46

    1. Introduction to Java

    A Brief History of Java: -Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, andMike Sheridan at Sun Microsystems, Inc.in 1991.It took 18 months to develop thefirst working version. This language was initially called Oak but was renamed Java in 1995.Between the initial implementation of Oak in the fall of 1992 and the publicannouncement of Java in the spring of 1995,many more people contributed to thedesign and evolution of the language.

    Initial purpose of this language development is not Internet. Actually thislanguage is designed for embedded software, which is used in Control system andElectronic devices. At the same time the concept of WWW is emerging in the market,

    which requires a platform independent and portable language. Because of platformindependency and portability java is used for Internet. Now java is used in embeddedsoftware, Internet Applications and Business applications development.

    Features of Java1.Simple and Powerful

    The syntaxes of Java are almost similar to C and C++ so java is easy tolearn C and C++ programmer.

    To run a Java program it requires a less hardware specification than any other

    language.2.Compiled and InterpretedActually programming languages are compiled or interpreted but java is

    compiled as well as interpreted language. Java enables the creation of cross-platformprograms by compiling into an intermediate representation called Java bytecode. Thiscode can be interpreted on any system that provides a Java Virtual Machine.3.Secure

    While downloading applications from Internet there is no chance to attach avirus with Java Applications and Applets. Java Runtime System provides Bytecodeverifier, which will, checks complete code before execution of program.

    4.Portable

    We can design java programs on any type of machine also we can run javaprograms on any Machine.

    When an applet is encountered on a Web page (if the user's browser can handle Java),the browser downloads the applet along with the text and images on the page. Theapplet then runs on the user's computer. This act should raise a red flag-danger!Danger! -Because a lot of harmful things can occur when programs are executed:viruses, Trojan horses, the Microsoft Network, and so on.

  • 8/14/2019 Core Java Index

    6/46

    5.Platform Independent

    When java program is compiled it will not generate directly anexecutable code like C and C++. Rather when java program is compiled it compiler

    generates a byte code which can run on any platform (Operating System). Bytecode isexecuted by JVM (Java Virtual Machine). JVM may differ from platform to platform.But all JVM interprets same bytecode. JVM generates Native code, which canunderstood by Processors.6. Multithreading

    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.

    7. Garbage Collection

    In other languages when object is allocated memory space at runtime thatobject will not free automatically. These objects are manually freed from the memory.

    Java Runtime provides a utility called Garbage Collector (gc method). WhenJVM reaches a free time it will run gc method, which will checks the scope of allobjects, stored in the memory. Garbage Collector frees all memory allocated byunused objects and make chance for allocation of new objects.

    8.Distributed Environment

    Internet is used in Distributed Environment. In network environmentcommunication is going on through protocols. Internet uses TCP/IP protocol for

    communication. Java can understand TCP/IP protocols.

    9. Database Support

    Database Managements Systems are used in Business Application forpermanent storage of data. Java provides inbuilt tools for database communication.

    Java ComponentsByteCode and JVMThe key that allows Java to solve both the security and the portability problems just

    described is that the output of a Java compiler is not executable code. Rather, it isbytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM).Bytecode is stored in class file. That is, in its standard form, the JVM is an interpreter

    for bytecode. This may come as a bit of a surprise. As you know, C++ is compiled toexecutable code. In fact, most modern languages are designed to be compiled, notinterpreted mostly because of performance concerns. However, the fact that a Java

    program is executed by the JVM helps solve the major problems associated withdownloading programs over the Internet.Translating a Java program into byte code helps makes it much easier to run a

    Program in a wide variety of environments. The reason is straightforward: only the

  • 8/14/2019 Core Java Index

    7/46

    JVM needs to be implemented for each platform. Once the run-time package exists fora given system, any Java program can run on it. Remember, although the details of theJVM will differ from platform to platform, all interpret the same Java byte code. If aJava program were compiled to native code, then different versions of the same

    program would have to exist for each type of CPU connected to the Internet. This is,of course, not a feasible solution. Thus, the interpretation of bytecode is the easiestway to create truly portable programs.

    JDK and JDK tools.JDKOf course, in order to write Java applications or applets, you need more than alanguage-you need the tools that let you write, test, and debug your programs. Thissection gives a very high-level overview of the various Java tools that come with theJava Developer's Kit

    JDK toolsCompilerThere is, of course, a Java compiler, named javac. The Java compiler takes inputsource code files (these files typically have the extension .java) and converts them intocompiled byte code files

    InterpreterThe Java interpreter can be used to execute Java applications. The interpreter

    translates byte codes directly into native code. (program actions)

    DebuggerThe Java debugger, jdb, enables you to debug your Java classes. Unfortunately, theJava debugger is a throwback to the pre-GUI debugger dark ages of programming.The Java debugger is a command-line debugger that is enough to make you wish foreven the 1988 version of CodeView. However, you can use the jdb to set breakpoints,inspect objects and variables, and monitor threads

    Header File GeneratorBecause Java is a new language and must fit in a world dominated by C and C++,included in Java is the capability to use native C code within a Java class. One of thesteps in doing this is using the Java header file generator, javah.

    Applet ViewerIf you will be writing Java applets, you will definitely want to become familiar withthe Applet Viewer. This small program provides a real Java environment for testingapplets. It loads the HTML file in which the applet has been embedded and displaysthe application in a browser-like window

    Java and Internet

    Current Web development technologies excel at displaying this type of page. Much of

    human communication is passive, static, or both. A highway billboard is a perfectexample of a conventional means of communication that is both passive and static.

  • 8/14/2019 Core Java Index

    8/46

    Just as not all billboards will go the way of Burma Shave, not all passive, staticWWW content needs to become active and dynamic (the opposites of passive andstatic).

    However, Java is an enabling technology that allows for the creation of more powerfulpages. Continuing with the example of a page that shows the price of a stock at agiven point in time, you could use Java to create a page that shows a graph of a stock's

    price over time and have that graph continue to update in real time while you browsethe page. This is where Java comes in-because Java is a full-featured programminglanguage, Web pages like this become much more feasible. Sun Microsystems hascreated a page that does exactly this.

    First Java Programclass First

    { public static void main(String args[]){

    System.out.pritln (Welcome to java programming world);}

    }How to run above program

    1) Type this file in any text editor and save this file as First.java.2) Compile this file as

    C:\jdk1.2\bin>javac First. java

    3) Run this file asC:\jdk1.2\bin> java First

    Explanation of above program:-class First

    Here class is the keyword used to define the classes in javaFirst is the class name (Identifier) By convention class names first letter

    is the upper case Letter in Java.

    public static void main(String args[])

    public is the access specifier allows us to call the main method out of this class.static is the keyword allows us to call this method without creating an instance

    of this class.voidindicates main method does not return any value.main is the name of method which indicated main method does not return

    any value.

    String args[]

    Is the array of string which values are passed at commandline

    While interpretation of this program.

  • 8/14/2019 Core Java Index

    9/46

    System.out.println(Welcome to java programming world);println is the method defined in PrintStream class, allows us to print any string

    or values of variables on standard output device (Monitor).out is the static object of PrintStream class defined in System class.System.out.printlnAbove method prints the specified string or results of calculations on output

    stream. Here Welcome to java programming world is printed on output stream.

    OOP principles1. Encapsulation

    2. Polymorphism

    3. Inheritance

    Encapsulation

    Encapsulations is the mechanism that binds code and data together,and

    keep safe from outside interference and missue. Everything that the software objectknows and can do is expressed by the variable and methods within that object.

    Inheritance

    Inheritance is the process of creating a new class(object) from existingclass(object) where newly created class is known as child or derived or sub class andalready existing class is known as parent or base or super class. Child class has theability to access all member functions and attributes of base class. Also it can includeits own data member and member functions. Code reusability is the key advantage ofinheritance.Polymorphism

    Poly means many and morphism means forms.We can use the same name formultiple tasks. For example we can specify the same name for different functions.

    Types of Java Program

    There are 2 types of java programs1.ApplicationAn Application is a program that runs on a computer under the operating system ofthat computer. That is, an application created by java is like one created using C or C++. Application program provides CLI (Command line Interface) and GUI (GraphicalUser Interface).

    2.AppletApplet is a special program designed to be transmitted over the internet and executedon java compatible web browsers. Actually it is a java program, dynamicallydownloaded across Internet just like image, sound file or video clip.

  • 8/14/2019 Core Java Index

    10/46

    Question Bank1. Why java is popular for Internet?2. Why java is platform independent?3. Explain features of java.

    4. Explain JVM and Bytecode5. Explain Different Components of JDK6. Why java is not fully object oriented programming language?7. Why java programs class name and file name should be same?

    8.Explain Object Oriented Principles.9.Explain public static void main(String args[])10. Explain types of Java Programs.

  • 8/14/2019 Core Java Index

    11/46

    2.Java Programming Features

    Character setJava Program is created using set of characters. These characters

    are called as Character set of Java. Javas character set includes

    A-------Z 26 Charactersa---------z 26 characters0---------9 10 digitsSpecial characters 32 characters

    ------------------94 characters

    TokensJava Program is formed by the combination of above characters. The word formedfrom the character set is called token.Following are the different types of tokens in java program.

    Keywords

    Identifiers

    Constants

    Operators

    Punctuation Symbols

    IdentifierAn identifier is a word used by a programmer to name a variable, method and class.Keywords are reserved words may not be used as identifier.Following are some valid identifiersaverage, net_pay, withdrawamount etc

    Some invalid identifiers3-mod2, $amount, #time etc

    VariableVariable is a given name to the memory location where the values are stored.The value of the variable can be changed during the programs execution.

    Rules for variable declaration Variable name should be start with alphabet.

    No special characters are used in variable name except under score( _

    Keywords of java cannot be used as a variable name.

    White spaces are not allowed in variable name.

    Java is case sensitive language. Hence uppercase and lowercase alphabetsare treated as different.

    By convention variable names are declared in small case letters.

  • 8/14/2019 Core Java Index

    12/46

    KeywordsKeywords are special reserved words provided by language developers whose

    meaning is already known to the compiler and interpreter. Keywords cannot be used

    as a variable name, method name and class name because we are assigning a newmeaning to that words, which is not allowed by java.Actually java contains 60 keywords out of them 49 are used to date. Keywords arealso called reserved words.

    abstract continue goto package synchronized

    assert private this interface class

    default protected throw Static floatif public throws long nativeboolean else instanceof char super

    do byte return finally while

    implements transient case strictfp const

    break extends int volatile for

    double short catch switch newimport final try void

    LiteralsUsing a literal representation of it creates a constant value in Java.Here are different types of literals

    1) Integer Literals

    2) Floating Literals3) Character and String Literals4) Boolean Literals

    100 98.6 X This is a test trueLeft to right, the first literal specifies an integer, the next is a floating-point value, thethird is a character constant fourth is a string a and last is boolean literal. A literal can

    be used anywhere a value of its type is allowed.

    Data TypesWhen we are declaring variables we should specify its type of the variable, itmeans what type of data the variable contains and how much memory space isrequired to store that value.The data types are categorized in following categories.1) Integer2) Floating point3) Character4) Boolean

  • 8/14/2019 Core Java Index

    13/46

    Integer data type

    Basically integer data types are the data type, which always containswhole nos

    INTEGER TYPE SIZE CAPACITY

    byte 8 bits -128 to 127short 16 bits -32768 to 32767

    int 32 bits -231 to 231-1

    long 64 bits -2 63 to 263-1

    Floating Data TypesFloating data types are the data types, which always contain numbers with

    decimal point.Float data types further divided in following categories.

    FLOAT TYPE SIZE CAPACITY

    float 32 bits 3.40282347E+38 F to-3.40282347E+38 F

    double 64 bits 1.79769313486231570E308to-1.79769313486231570E308

    Character Data TypeIn java char data type is used to store character value. Java uses Unicode character setto represent characters. The size of char data type is 2 bytes ranging from 0 to 65535.

    Examplechar c=a;

    Declaring constant Variables in javaThe value of constant variable cannot change throughout the program. Constants aredeclared in java by using finalkeyword. By convention keywords are declared inuppercase only.

    Examplefinal float PI=3.14F;

    Using Command-Line ArgumentsSometimes you will want to pass information into a program when you run it.Thisis accomplished by passing command-line arguments to main().A command-lineargument is the information that directly follows the program s name on thecommand line when it is executed. To access the command-line arguments inside aJava program is quite easy they are stored as strings in the String array passed tomain()

  • 8/14/2019 Core Java Index

    14/46

    OperatorsOperators are special symbols used for mathematical, logical and bitwise

    operationsFollowing are the categories of operators

    1) Unary operatorsA Unary operator operates on only one operand.

    2) Binary Operators

    A binary operator operates on 2 operands.3) Ternary operators

    A ternary operator operates on 3 operands.

    Following are the different types of operators1) Arithmetic Operators

    2) Relational Operators

    3) Logical Operators4) Bitwise Operators

    5) Shift Operators

    Arithmetic operatorsArithmetic operators are used to perform arithmetic operations.

    Following table shows the arithmetic operatorsHere consider int a=20, b=10;

    OPERATOR MEANNING EXAMPLE RESULT

    ++ Increment a++ a=21-- Decrement a-- a=19

    + Addition a+b 30

    - Subtraction a-b 10

    * Multiplication a*b 200

    / Division a/b 2

    % Modulus a%3 2

    += Addition Assignment a+=10 a=30

    -= Subtraction Assignment a-=10 a=10

    *= Multiplication Assignment A*=2 a=40/= Division Assignment a/=2 a=10

    %= Modulus Assignment a%=2 a=2

    Relational OperatorsThese operators are used to compare two values. These operators always returnone Boolean value after execution of relational expression. Following is the list ofrelational operators used in java. Relational operators are used with conditionalstatements.

    Consider

    int i=20,j=10;

  • 8/14/2019 Core Java Index

    15/46

    OPERATOR MEANING EXAMPLE RESULT

    < Less than a Greater than a>b True

    = = Equal to a= =b False

    ! = Not equal to a!=b True< = Less than equal to a= Greater than equal to a>=b True

    Logical operatorsThe Logical operators are used to compare more than conditions simultaneouslyi.e. we can combine more than one condition and form one unique condition.

    Operator Meaning&& Logical AND| | Logical OR! Logical NOT

    && Operator returns True if all specified conditions are true.| | Operator returns True if one of the conditions is true among specifiedconditions.! Operator negates the specified expression.

    The Bitwise Logical OperatorsJava defines several bitwise operators which can be applied to the integer types,long,int ,short ,char ,and byte .These operators act upon the individual bits of theiroperands.They are summarized in the following table:Operator Meaning

    ~ Bitwise unary NOT& Bitwise AND

    | Bitwise OR^ Bitwise exclusive ORThe bitwise logical operators are &, |, ^, and ~. The following table shows theoutcome of each operation. In the discussion that follows, keep in mind that the

    bitwise operators are applied to each individual bit within each operand.

  • 8/14/2019 Core Java Index

    16/46

    A B A |B A &B A B ~A

    0 0 0 0 0 11 0 1 0 1 0

    0 1 1 0 1 11 1 1 1 0 0

    The Bitwise NOTAlso called the bitwise complement,the unary NOT operator,~,inverts all of the

    bits ofits operand.For example,the number 42,which has the following bit pattern:00101010

    becomes11010101

    after the NOT operator is applied.The Bitwise ANDThe AND operator,&,produces a 1 bit if both operands are also 1.A zero is

    produced in all other cases.Here is an example:

    00101010 42& 00001111 15

    --------------00001010 10

    The Bitwise ORThe OR operator,|,combines bits such that if either of the bits in the operands isa 1,then the resultant bit is a 1,as shown here:

    00101010 42

    | 00001111 15--------------00101111 47

    UAGE

    The Bitwise XORThe XOR operator,^,combines bits such that if exactly one operand is 1,then the resultis 1.Otherwise,the result is zero.The following example shows the effect of the ^.Thisexample also demonstrates a useful attribute of the XOR operation.Notice how the bit

    pattern of 42 is inverted wherever the second operand has a 1 bit.Wherever the secondoperand has a 0 bit,the first operand is unchanged.You will find this property usefulwhen performing some types of bit manipulations.

    00101010 42

    ^ 00001111 15

    -------------00100101 37

  • 8/14/2019 Core Java Index

    17/46

    Bitwise Shift OperatorsJava provides > shift operators for shifting of bits. Shifting of bits is used

    in control system. Shift operators are always used with integer data types.

    The Left ShiftThe left shift operator > 2; // a now contains 8

    Control StatementsA programming language uses control statements to cause the flow of execution toadvance and branch based on changes to the state of a program. Java s programcontrol statements can be put into the following categories: selection, iteration, and

    jump. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iterationstatements enable program execution to repeat one or more statements

  • 8/14/2019 Core Java Index

    18/46

    Selection Statements or conditional statementsJava supports two selection statements :ifand switch .These statements allow you to

    control the flow of your program s execution based upon conditions known onlyduring run time. You will be pleasantly surprised by the power and flexibilitycontained in these two statements.

    if statementThe if statement is Java s conditional branch statement. It can be used to route

    program execution through two different paths.Here is the general form of the ifstatement:if (condition ){

    //Block of java code

    }else{

    // block of code}Here, eachstatementmay be a single statement or a compound statement enclosed incurly braces (that is, a block). The condition is any expression that returns a booleanvalue. The else clause is optional. The ifworks like this: If the condition is true, then

    block1is executed. Otherwise, Block2 (if it exists) is executed. In no case will bothstatements be executed.For example, consider the following:int a, b;if(a < b)

    a = 0;else

    b = 0;

    Here, ifa is less than b ,then a is set to zero. Otherwise, b is set to zero. In no case arethey both set to zero.Most often, the expression used to control the ifwill involve the relational operators.

    THThe if-else-if LadderA common programming construct that is based upon a sequence of nested ifs is theif-else-ifladder.It looks like this:if(condition ){

    Block of code;

    }else if(condition)

    {Block of code;

  • 8/14/2019 Core Java Index

    19/46

    }else if(condition ){

    Block of code;

    }--------else{

    Block of code}

    THEE The if statements are executed from the top down. As soon as one of theconditions controlling the ifis true ,the statement associated with that ifis executed,and the rest of the ladder is bypassed. If none of the conditions is true, then the finalelse statement will be executed. The final else acts as a default condition; that is, if allother conditional tests fail, then the last else statement is performed. If there is no finalelse and all other conditions are false ,then no action will take place.

    switch statementThe switch statement is Java s multiway branch statement. It provides an easy wayto dispatch execution to different parts of your code based on the value of anexpression. As such, it often provides a better alternative than a large series ofif-else-ifstatements. Here is the general form of a switch statement:switch (expression )

    {case value1 :

    //statement sequencebreak;

    case value2 ://statement sequence

    break;...

    case valueN://statement sequence

    break;default:

    //default statement sequence}The expression must be of type byte ,short ,int ,orchar ;each of the values specifiedin the case statements must be of a type compatible with the expression. Each casevalue must be a unique literal (that is,it must be a constant,not a variable). Duplicatecase values are not allowed. The switch statement works like this:The value of the

    expression is compared with each of the literal values in the case statements.If amatch is found,the code sequence following that case statement is executed.If none of

  • 8/14/2019 Core Java Index

    20/46

    the constants matches the value of the expression,then the default statement isexecuted.However,the default statementis optional.If no case matches and no default is present,then no further action is taken.The break statement is used inside the switch to terminate a statement sequence.When a breakstatement is encountered,execution branches to the first line of codethat follows the entire switch statement. This has the effect of jumping out of theswitch .

    Looping Statements or Iteration statementsIteration StatementsJava s iteration statements are for ,while ,and do-while .These statements create whatwe commonly call loops.As you probably know,a loop repeatedly executes the sameset of instructions until a termination condition is met.As you will see,Java has a loopto fit any programming need.

    while LoopThe while loop is Java s most fundamental looping statement.It repeats a statement or

    block while its controlling expression is true.Here is its general form:while(condition ){

    //body of loop}

    The condition can be any Boolean expression. The body of the loop will be executed

    as long as the conditional expression is true. When condition becomes false, controlpasses to the next line of code immediately following the loop. The curly braces areunnecessary if only a single statement is being repeated.

    do-while loopAs you just saw, if the conditional expression controlling a while loop is initiallyfalse, then the body of the loop will not be executed at all. However, sometimes it isdesirable to execute the body of a while loop at least once, even if the conditionalexpression is false to begin with. In other words, there are times when you would liketo test the termination expression at the end of the loop rather than at the beginning.Fortunately, Java supplies a loop that does just that: the do-while .The do-while loop

    always executes its body at least once, because its conditional expression is at thebottom of the loop. Its general form is

    do {

    //body of loop}while (condition );

    Each iteration of the do-while loop first executes the body of the loop and thenevaluates the conditional expression. If this expression is true, the loop will repeat.

    Otherwise, the loop terminates. As with all of Java s loops, condition must be aBoolean expression.

  • 8/14/2019 Core Java Index

    21/46

    LANGUAGE

    for loopYou were introduced to a simple form of the for loop in Chapter 2.As you will see, itis a powerful and versatile construct. Here is the general form of the for statement:for(initialization ;condition ;iteration ){

    //body}If only one statement is being repeated, there is no need for the curly braces. The forloop operates as follows. When the loop first starts, the initializationportion of theloop is executed. Generally, this is an expression that sets the value of the loopcontrol variable, which acts as a counter that controls the loop. It is important tounderstand that the initialization expression is only executed once. Next, condition isevaluated. This must be a Boolean expression. It usually tests the loop control variableagainst a target value. If this expression is true, then the body of the loop is executed.If it is false ,the loop terminates. Next, the iterationportion of the loop is executed.This is usually an expression that increments or decrements the loop control variable.The loop then iterates, first evaluating the conditional expression, then executing the

    body of the loop, and then executing the iteration expression with each pass .Thisprocess repeats until the controlling expression is false.

    break and continue statementsUsing break to Exit a LoopBy using break ,you can force immediate termination of a loop, bypassing theconditional expression and any remaining code in the body of the loop. When a break

    statement is encountered inside a loop, the loop is terminated and program controlresumes at the next statement following the loop .

    Using continueSometimes it is useful to force an early iteration of a loop.That is,you might want tocontinue running the loop,but stop processing the remainder of the code in its body forthis particular iteration.This is,in effect,a goto just past the body of the loop,to the loops end.The continue statement performs such an action.In while and do-while loops,acontinue statement causes control to be transferred directly to the conditionalexpression that controls the loop.In a for loop,control goes first to the iteration portionof the for statement and then to the conditional expression.For all three loops,anyintermediate code is bypassed.

  • 8/14/2019 Core Java Index

    22/46

    Question Bank1. Explain different data types of Data types with their memory size.2. Explain Following operators.

    i. Arithmetic Operators

    ii. Bitwise Operatorsiii. Relational Operatorsiv. Logical Operatorsv. Shift Operators

    3. Explain Conditional statements with syntaxes4. What do you mean by looping statements? Explain Looping statements used in

    java programming5. Why java avoids the use of goto statement?6. Explain break and continue statement7. Explain the process of data type conversion in java.

    8. Explain the advantages of switch case statement over ladder if else if statement9. Explain the following termsKeywordsIdentifiersTokenLiteralCharacter set

    10. How we can store hexadecimal and octal nos in integer variables11. Explain the use of bitwise operators.

  • 8/14/2019 Core Java Index

    23/46

    3.Classes and Objects

    Class and general structure of classThe class forms the basis for object-oriented programming in Java. Any concept youwish to implement in a Java program must be encapsulated within a class. The class isat the core of Java.

    The most important thing to understand about a class is that it defines a newdata type. Once defined, this new type can be used to create objects of that type. Thus,a class is a template for an object, and an object is an instance of a class. In simplewords class is a user defined data type which binds code and data together

    A class is declared by use of the class keyword. The general form of a classdefinition is shown here:class classname

    {

    type instance-variable1 ;type instance-variable2 ;-------type instance-variableN;constructor(paramlist){

    //initialization code}

    type methodname1 (parameter-list){

    //body of method}type methodname2 (parameter-list){

    //body of methodTHE }

    type methodnameN(parameter-list){

    //body of method}

    }

    Declaring Objects and Object InitializationAs just explained, when you create a class, you are creating a new data type. You canuse this type to declare objects of that type. However,obtaining objects of a class is a

    two-step process.First,you must declare a variable of the class type.This variable doesnot define an object.Instead,it is simply a variable that can referto an object.Second,

  • 8/14/2019 Core Java Index

    24/46

    you must acquire an actual,physical copy of the object and assign it to thatvariable.You can do this using the new operator.The new operator dynamicallyallocates (that is,allocates at run time)memory for an object and returns a reference toit.This reference is,more or less,the address in memory of the object allocated by new. This reference is then stored in the variable.Thus,in Java,all class objects must bedynamically allocated.Following is the syntax of object declaration in java.

    Classname object; //Object declaration

    e.g.

    Student s;object=new Classname([param list]); //object initialization

    e. g

    s=new Student();

    Access Specifiers/Modifiers/ControlsEncapsulation links data with the code that manipulates it.However, encapsulation

    provides another important attribute:access control. Through encapsulation,you cancontrol what parts of a program can access the members of a class. By controllingaccess,you can prevent misuse. For example, allowing access to data only through awell-defined set of methods, you can prevent the misuse of that data.

    Follwingis the list of access specifiers used in java

    1) private Private members can be accessed only within the class in which it isdefined. Private members are declared usingprivate keyword.

    2) publicPublic members can be accessed within the class in which it is declared as well asanywhere outside the class through an instance of class. Here classes can be same

    package or different package. Public members are declared by using publickeyword.

    3) protectedProtected members can be accessed within the class in which it is declared as well as

    in its child class but here base class and child class should be within the samepackage. Protected members are declared by usingprotectedkeyword.

    4)friendlyWhen a member is declared in a class without any access specifier that is by defaultconsidered is a friendly. Friendly access specifier behaves somewhat like public.Friendly members are accessed within a class in which it is declared as well asanother classes within the same package. Friendly members cannot be accessedoutside the package in which it is declared.

    5)public protectedWhen a member is declared withpublic protectedaccess specifier that member can

    be accessed within the class as well as in child class. Here child class may be indifferent package.

  • 8/14/2019 Core Java Index

    25/46

    Adding methods to the classAs mentioned at the beginning of this chapter,classes usually consist of two thingsinstance variables and methods.The topic of methods is a large one because Java givesthem so much power and flexibility.In fact,much of the next chapter is devoted to

    methods.However,there are some fundamentals that you need to learn now so that youcan begin to add methods to your classes.

    This is the general form of a method:type name (parameter-list){

    //body of method}Here, type specifies the type of data returned by the method.This can be any validtype, including class types that you create.If the method does not return a value,its

    return type must be void .The name of the method is specified by name.This can beany legal identifier other than those already used by other items within the currentscope. The parameter-list is a sequence of type and identifier pairs separated bycommas. Parameters are essentially variables that receive the value of the arguments

    passed to the method when it is called.If the method has no parameters,then theparameter list will be empty. Methods that have a return type other than void return avalue to the calling routine using the following form of the return statement:return value ;Here,value is the value returned.

    ConstructorConstructor is a special type of function which have same name as class in which it isdeclared. Once a constructor is defined it is automatically called immediately after theobject is created. Following are the rules for constructor declaration

    Constructor should have same name as that of its class name.

    Constructor should not return any value.

    Constructor may take parameters

    Constructor should not be abstract or static.

    Need of ConstructorA class contains one of the process which requires some data and code. Data is storedin the form of instance variables of class. Means it will not execute a process definedin the class without initializing the variables of class. It is difficult to initialize all theclass variables by using like getdata() method as used in all programs. So we candefine a constructor which will call automatically when the object is created of thatclass and initializes the variables of class.

    Parameterized constructorIf you want to assign different values to the instance variables when different

    objects are created. So we make constructor which takes some argument whose value

  • 8/14/2019 Core Java Index

    26/46

    will be assigned to variable. In short Constructor which have arguments are known asparameterized constructor.

    Following is the general form of constructorNameOfClass(data type arg1,data type arg2,data type arg3----------data

    type argn) The general structure explains that the NameOfClass will be thesame name of class in which we are declaring constructor. Here arg1,arg2--------argn represent the list of arguments used in constructor like wedeclare arguments in method and the type represents the data type of arguments.It is not mandatory that constructor must have the arguments, the constructormay be without parameters. For example, if class Student name is Student thenthe constructor can be declared as

    Student( int roll ,String name){

    //Initialization}//Parameterized Constructor

    OrStudent(){

    // Initialization}//Without parameter constructor

    this KeywordSometimes a method will need to refer to the object that invoked it.To allow this, Javadefines the this keyword. this can be used inside any method to refer to the currentobject. That is, this is always a reference to the object on which the method wasinvoked. You can use this anywhere a reference to an object of the current class typeis permitted.

    Instance variable hidingyou can have local variables, including formal parameters to methods,which overlapwith the names of the class instance variables.However,when a local variable has thesame name as an instance variable,the local variable hides the instance variable.

    Overloading MethodsIn Java it is possible to define two or more methods within the same class that sharethe same name, as long as their parameter declarations are different. When this is thecase, the methods are said to be overloaded, and the process is referred to as methodoverloading. Method overloading is one of the ways that Java implements compiletime polymorphism.When an overloaded method is invoked, Java uses the type and/or number ofarguments as its guide to determine which version of the overloaded method toactually call. Thus, overloaded methods must differ in the type and/or number of their

    parameters. While overloaded methods may have different return types, the returntype alone is insufficient to distinguish two versions of a method. When Java

  • 8/14/2019 Core Java Index

    27/46

    encounters a call to an overloaded method, it simply executes the version of themethod whose parameters match the arguments used in the call.

    Static members of class

    There will be times when you will want to define a class member that will be usedIndependently of any object of that class. Normally a class member must be accessedonly in conjunction with an object of its class. However, it is possible to create amember that can be used by itself, without reference to a specific instance. To createsuch a member, precede its declaration with the keyword static. When a member isdeclared static, it can be accessed before any objects of its class are created, andwithout reference to any object. You can declare both methods and variables to bestatic .The most common example of a static member is main (). main()is declaredas staticbecause it must be called before any objects exist. Instance variables declaredas static are, essentially, global variables. When objects of its class are declared, no

    copy of a static variable is made. Instead, all instances of the class share the samestatic variable.

    Methods declared as static have several restrictions:

    They can only call otherstatic methods.

    They must only access static data.

    They cannot refer to this orsuper in any way.

    If you need to do computation in order to initialize your static variables, you candeclare a static block, which gets executed exactly once, when the class is firstloaded.

    Introducing Nested and Inner ClassesIt is possible to define a class within another class; such classes are known as nestedclasses. The scope of a nested class is bounded by the scope of its enclosing class.When you define nested classes, inner class can access members of outer class butouter class cannot access members of inner class.

    Following are the type of inner class1) Static inner class2) Non static inner class

    A static nested class is one which has the static modifier applied. It has access tomembers of inner class and only static members of outer class.The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer classand may refer to them directly in the same way that other non-static members of theouter class do. Thus, an inner class is fully within the scope of its enclosing class.

  • 8/14/2019 Core Java Index

    28/46

    Question Bank

    1. Explain class and its general syntax.2. Explain Object Oriented Programming principles.

    3. Explain Access modifiers.4. Explain scope of variable.5. Explain the process of method overloading.6. Explain Constructor and its need.7. Explain packages with its types.8. In what situation parameterized constructors are used?9. Explain static members of class10.Explain Nested and inner classes with their types.11.Explain this keyword.12.Explain methods syntax? How we can add methods in the class?

    13.How object is created in java? Why it is required?

  • 8/14/2019 Core Java Index

    29/46

    4.InheritanceInheritanceInheritance is one of the measure principles of object-oriented programming becauseit allows the creation of hierarchical classifications. Using inheritance, you can creategeneral class that defines traits common to a set of related items. Other, more specificclasses can then inherit this class, each adding those things that are unique to it. In theterminology of Java, a class that is inherited is called asuperclass. The class that doesthe inheriting is called a subclass. Therefore,a subclass is a specialized version of asuperclass.It inherits all of the instance variables and methods defined by thesuperclass and adds its own, unique elements.Inheritance BasicsTo inherit a class, you simply incorporate the definition of one class into another byusing the extends keyword. To see how, let s begin with a short example. The

    following program creates a superclass called StudentInfo and a subclass calledStudent. . Notice how the keyword extends is used to create a subclass of Student.class StudentInfo{

    protected String name;protected int roll,mark1,mark2;StudentInfo(){

    name="Raj";roll=101;

    mark1=78;mark2=56;

    }int total(){

    return mark1+mark2;}void display(){

    System.out.println("Name="+name);

    System.out.println("Roll="+roll);System.out.println("Total Marks="+total ());

    }}class StudentAvg extends StudentInfo{

    float avg;String address;StudentAvg(String n,int r,int m1,int m2,String a){

    name=n;roll=r;

  • 8/14/2019 Core Java Index

    30/46

    mark1=m1;mark2=m2;address=a;

    }float calAvg(){

    avg=total()/2;return avg;

    }void show(){

    display();System.out.println("Average="+calAvg());System.out.println("Address="+address);

    }}class studentdemo{

    public static void main(String sp[]){

    StudentAvg obj=new StudentAvg("Yash",101,78,49,"Solapur");obj.show();

    }}

    A Superclass Variable Can Reference a SubclassObjectA reference variable of a superclass can be assigned a reference to any subclassderived from that superclass.You will find this aspect of inheritance quite useful in avariety of situations.For example,consider the following:class Base{

    void show(){

    System.out.println(I am Base);

    }}class Child extends Base{

    void display(){

    System.out.println(I am child);}

    }class BaseChild

    {public static void main(String args[])

  • 8/14/2019 Core Java Index

    31/46

    {Base b=new Base();

    b.show();b=new Child();b.display();

    }}

    Method OverridingIn a class hierarchy, when a method in a subclass has the same name and typesignature as a method in its superclass, then the method in the subclass is said tooverride the method in the superclass. When an overridden method is called fromwithin a subclass, it will always refer to the version of that method defined by thesubclass. The version of the method defined by the superclass will be hidden.Consider the following:

    Super KeywordIn java there is a keyword named super which is used in inheritance. super keywordis used for the following purposes.

    1. To access the private members of base class in child class by calling theconstructor of base class in child class. But the constructor calling statementshould be the first statement in the child constructor definition.

    2. To access the members of base class in the child class having same name.3. To call the method of base class in the child class having same name.

    Following program demonstrates the use of super keyword.

    // Method overriding and super keywordclass A{

    int i, j;A(int a, int b){

    i = a;j = b;

    }// display i and jvoid show(){

    System.out.println("i and j: " + i + " " + j);}

    }class B extends A{

    int k;B(int a, int b, int c){

    super(a, b);

  • 8/14/2019 Core Java Index

    32/46

    k = c;}

    // display k this overrides show() in Avoid show(){

    System.out.println("k: " + k);}

    }class Override{

    public static void main(String args[]){

    B subOb = new B(1, 2, 3);subOb.show(); // this calls show() in B

    }}

    final keywordfinal is one of the keyword used in java program for following purposes

    1. To declare the constant variables in java.e.g. final float PI=3.14F;

    2. To prevent a method from overriding, e .g if one of the method is defined in thebase class as a final then that method cant be override in the child class.

    3. To prevent the class from inheritance. If one of the class is declared as finalthen any other classes cant inherit to the final classes.

    Following program demonstrates the use of final keyword.final class Area{

    final float PI=3.14F;final float calArea(float r){

    return PI*r*r;}

    void display(){

    System.out.println(Area of circle=+calArea(5.6F));{

    }class FinalDemo{

    public static void main(String str[]){

    Area obj=new Area();

    Obj.display();}

  • 8/14/2019 Core Java Index

    33/46

    }

    In the above program PI variable declared as a final(constant) e.g the value ofthe PI variable cannot be changed. Area class is also declared as a final so no anyother classes can inherit the Area class. CalArea() method is declared as a final meansthe calArea cannot be overridden in the child class.

    Dynamic method dispatchDynamic method dispatch is the mechanism by which a call to an overridden methodis resolved at run time, rather than compile time. Dynamic method dispatch isimportant because this is how Java implements run-time polymorphism. Let s begin

    by restating an important principle:a superclass reference variable can refer to asubclass object. Java uses this fact to resolve calls to overridden methods at run time.Here is how. When an overridden method is called through a superclass reference,

    Java determines which version of that method to execute based upon the type of theobject being referred to at the time the call occurs. Thus, this determination is made atrun time. When different types of objects are referred to, different versions of anoverridden method will be called. In other words, it is the type of the object beingreferred to (not the type of the reference variable) that determines which version of anoverridden method will be executed. Therefore, if a superclass contains a method thatis overridden by a subclass, then when different types of objects are referred tothrough a superclass reference variable, different versions of the method are executed.

    Following program demonstrates the use of Dynamic method dispatch.

    class Base{

    void display(){

    System.out.println(Hello from base class);}

    }class Child extends Base{

    void display()

    {System.out.println(Hello from child class);

    }}class DynamicDemo{

    public static void main(String args[]){

    Base b=new Base();b.display();b=new Child();

  • 8/14/2019 Core Java Index

    34/46

    b.display();}

    }Here in above program base class object b pints to the base class first time it will callsthe display method of base class. When base class object points to the child class thenit will calls the method of child class.

    Abstract classThere are situations in which you will want to define a superclass that declares thestructure of a given abstraction without providing a complete implementation of everymethod. That is, sometimes you will want to create a superclass that only defines ageneralized form that will be shared by all of its subclasses, leaving it to each subclassto fill in the details. Such a class determines the nature of the methods that thesubclasses must implement. One way this situation can occur is when a superclass is

    unable to create a meaningful implementation for a method. These methods aresometimes referred to as subclasser responsibility because they have noimplementation specified in the superclass. Thus, a subclass must override them itcannot simply use the version defined in the superclass. To declare an abstractmethod, use this general form:

    abstract type name(parameter-list);Any class that contains one or more abstract methods must also be declared abstract.To declare a class abstract, you simply use the abstract keyword in front of the classkeyword at the beginning of the class declaration. There can be no objects of anabstract class. That is, an abstract class cannot be directly instantiated with the new

    operator. Such objects would be useless, because an abstract class is not fully defined.Also, you cannot declare abstract constructors, or abstract static methods. Anysubclass of an abstract class must either implement all of the abstract methods in thesuperclass, or be itself declared abstract.Following program demonstrates the use of abstract classesabstract class Animal{

    abstract void travel();void show(){

    System.out.println(I am abstract);}

    }class Bird extends Animal{

    void travel(){

    System.out.println(I am bird);}

    }

    class Fish extends Animal{

  • 8/14/2019 Core Java Index

    35/46

    void travel(){

    System.out.println(I am Fish);}

    }class AbstractDemo{

    public static void main(String args[]){

    Bird b=new Bird();b.travel();b.show();Animal obj=new Fish();obj.travel();obj.show();

    }}

    In the above program Animal class is declared as abstract. In Animal classtravel method is declared as a abstract. Fish class and Bird class inheriting the Animalclass so Fish and Bird class overrides the travel method of Animal class.

    InterfaceJava does not support Multiple Inheritance but java achieves the technique of multipleInheritance by using a new notation called interface. By using interface we can define

    fully abstract class. That is, using interface, you can specify what a class must do, butnot how it does it. Interfaces are syntactically similar to classes, but they lack instancevariables, and their methods are declared without any body. In practice, this meansthat you can define interfaces, which dont make assumptions about how they areimplemented. Once it is defined, any number of classes can implement an interface.Also, one class can implement any number of interfaces. To implement an interface, aclass must create the complete set of methods defined by the interface. However, eachclass is free to determine the details of its own implementation. By providing theinterface keyword and a class can implement the interface by using implementskeyword.

    In short interface is a class like structure which contains only finalvariables and abstract methods though which java achieves the concept of multiple

    inheritance. Java allows you to fully utilize the one interface, multiple methods aspect of polymorphism.Following is the general form of interface.access interface identifier{

    return-type method-name1 (parameter-list );return-type method-name2 (parameter-list );

    type final-varname1 =value;

    type final-varname2 =value;.

  • 8/14/2019 Core Java Index

    36/46

    return-type method-nameN (parameter-list );type final-varnameN =value;

    }

    Following program demonstrates the use of interface in java.

    interface Area{

    float PI=3.14F;float calArea(float x, float y);

    }

    class Circle implements Area{

    public float calArea(float x,float y){return PI*x*x;}

    }class Rectangle implements Area{

    public float calArea(float x, float y)

    { return x*y;}

    }class InterfaceDemo{

    public static void main(String args[]){

    Circle c=new Circle();Rectangle r=new Rectangle ();

    float a1,a2;a1=c.calArea(3.4F,0);a2=r.calArea(4.5F,6.7F);System.out.println(Area of circle=+a1);System.out.println(Area of Rectangle=+a2);

    }}

  • 8/14/2019 Core Java Index

    37/46

    Question Bank1. Explain super keyword with its different uses in java.2. Explain final keyword.3. Explain method overriding.

    4. Differentiate method overloading and overriding5. Explain dynamic Method Dispatch.6. How multilevel inheritance is implemented in java.7. Explain abstract class. When they are used?8. Explain interface and its general structure.9. Explain finalize () method. Why it is always protected?10.Explain multilevel inheritance.

  • 8/14/2019 Core Java Index

    38/46

    5.Exception HandlingExceptionAnexception is a condition that is caused by run time error in the program when the

    java interpreter encounters an error such as dividing by zero; it creates an exceptionobject and throws it. In short Exceptions are javas predefined objects which areinstantiated by java runtime System whenever error occurs at runtime.

    Need of Exception HandlingBefore you learn how to handle exceptions in your program, it is useful to see whathappens when you don t handle them. This small program includes an expression thatintentionally causes a divide-by-zero error.class MyException{

    public static void main(String args[])

    {int d = 0;int a = 42 / d;

    }}When the Java run-time system detects the attempt to divide by zero, it constructs anew exception object and then throws this exception. This causes the execution ofMyException to stop, because once an exception has been thrown, it must be caught

    by an exception handler and dealt with immediately. In this example, we haven tsupplied any exception handlers of our own , so the exception is caught by the default

    handler provided by the Java run-time system. Any exception that is not caught byyour program will ultimately be processed by the default handler. The default handlerdisplays a string describing the exception, prints a stack trace from the point at whichthe exception occurred, and terminates the program.Here is the output generated when this example is executed.

    Java.lang.ArithmeticException: / by zero at Exc0.main (Exc0.java:4)

    Notice how the class name,Exc0; the method name, main ;the filename,Exc0.java ;and the line number,4 ,are all included in the simple stack trace.Also,notice that thetype of the exception thrown is a subclass of Exception calledArithmeticException ,which more specifically describes what type of error happened.

    If the exception object is not caught and handled properly, the interpreter will displayan error message and will terminate the program. If we want to continue the programwith the execution of the remaining code then we should try to catch the exceptionobject thrown by the error condition and display an appropriate message for takingcorrective actions. This task is known as Exception Handling

    The purpose of exception handling mechanism is to provide means to detectand report an exceptional circumstance so that appropriate action can be taken.

    To handle the exceptions in java program perform the following task.

    1. Find the problem (Hit the exception).2. Inform that an error information (Throw the exception)

    3. Receive the error information (Catch the exception)4. Take corrective actions (Handle the exceptions)

  • 8/14/2019 Core Java Index

    39/46

    Common java Exception classes1. ArithmeticException

    Throws when user or programmer is trying to divide the no by zero in javaprogram.

    2. ArrayIndexOutOfBoundsExceptionThrows when we are exceeding the array indexes.

    3. FileNotFoundException

    Throws when a program tries to attempt to access a non-existent file.4. IOException

    Caused by general I/O failures, such as inability to read from file or writ e tofile.

    5. NullPointerException

    Caused when we are accessing methods or members through a null object.(Non-initialized)

    6.OutOfMemoryExceptionCauses when there is no enough memory to allocate a new object.

    6. StringIndexOutOfBoundsException

    Throws when we are accessing a non-existent character from a string.7. IllegalArgumentExfeption

    Throws when we will pass the illegal arguments to the methods.8. IllegalThreadStateException

    Throws when threads are switching to illegal state.9. NumberFormatException

    Throws when we are trying to convert an invalid string to the no in java

    program.10. SQLException

    Throws while communicating with database management systems.

    try ---catch---finally constructThe try catchfinally construct is a technique of handling exceptions in

    java program.Following is the general structure of try-catch-finally constructtry{

    //block of java code which causes the exception}

    catch(ExceptionType1 obj){

    //block of java code which is executed when the exception is generated intry block

    }catch(ExceptionType2 obj2)

    {//block of java code which is executed when the exception is generated in

    try block}

  • 8/14/2019 Core Java Index

    40/46

    ------------------------------------------------------------------------------catch(ExceptionTypen objn)

    {

    //block of java code which is executed when the exception is generated intry block

    }finally

    {//block of java code which assures for guarantee execution

    }While executing the try block if exception is generated which matches with

    argument of catch, the statement in the curly braces that follow the catch keyword willbe executed. After executing these statements, the program will continue with the nextstatement.If the exception created does not match with the argument of catch, javaruntime system throws the exceptions and will terminates the programs execution.Finally, the block of code which included in the curly braces followed by the finally

    keyword will execute compulsory, no matter the exception is generated or not.

    Following program demonstrates how to handle the exceptions in java

    program.

    class Arithmetic {

    public static void main(String arg[]){int a,b,c=0;a=Integer.parseInt(arg[0]);

    b=Integer.parseInt(arg[1]);try{

    c=a/b;}catch(ArithmeticException ae){

    System.out.println("Second value should not be zero");}

    finally {System.out.println("Result="+c);}System.out.println("Exception Demo");}

    }If in the above userr will enter second value zero at commandline during the

    programs execution then java runtime system throws an Exception namedArithmeticException.

  • 8/14/2019 Core Java Index

    41/46

    Following program demonstrates the use of multiple catch statements in the

    java program.

    class MultipleCatchDemo{

    public static void main(String arg[]){

    int i,j,k=0;

    try{

    i=Integer.parseInt(arg[0]);j=Integer.parseInt(arg[1]);k=i/j;

    }catch(NumberFormatException ae){

    System.out.println("You should enter valid numeric value");}catch(ArrayIndexOutOfBoundsException e){

    System.out.println("You shoul pass 2 values at commandline");

    }catch(ArithmeticException ae)

    { System.out.println("Second value should not be zero");}finally{

    System.out.println("Result="+k);}

    }}

    Above program demonstrates the use of multiple catch blocks in a java program. While executing the program if user will not enters the values atcommand line then Java Interpreter throws ArrayIndexOutOfBoundsException, ifuser will enters a character value at commandline then it throws

    NumberFormatException, if user will enter a second value zero then it throwsArithmeticException. But at a time java can throw only one exception from a try

    block.

  • 8/14/2019 Core Java Index

    42/46

    throw keywordIn all above programs exceptions are thrown automatically by java

    runtime system when a runtime error occurs. Java also allows programmer tothrow exceptions manually on user defined situations. This task is done by the

    throw keyword.Following is the syntax of throw diagram.throw obj;

    Here obj is object of any subclass of java.lang.Throwable class.e.g.

    throw new Exception(Sal out of Range);

    Following program demonstrates the use of throw keyword in java program.

    class ThrowDemo{

    public static void main(String args[]){

    int sal=0;Exception e=new Exception("Salary out of range");

    try{sal=Integer.parseInt(args[0]);

    if(sal15000)throw e;

    }catch(Exception se){

    System.out.println(se.getMessage());}

    finally{

    System.out.println("Salary="+sal);}

    }}

    throws keywordIf a method is capable of causing an exception that it does not handle,it mustspecifythis behavior so that callers of the method can guard themselves against thatexception. You do this by including a throws clause in the method s declaration.Athrows clause lists the types of exceptions that a method might throw.This isnecessary for all exceptions,except those of type Error orRuntimeException ,or anyof their subclasses. All other exceptions that a method can throw must be declared in

  • 8/14/2019 Core Java Index

    43/46

    the throws clause.If they are not,a compile-time error will result. This is the generalform of a method declaration that includes a throws clause:type method-name(parameter-list)throws exception-list{

    //body of method}

    Here,exception -list is a comma-separated list of the exceptions that a method can

    throw.

    Following program demonstrates the use of throws keyword in java programs.

    class ThrowsDemo{

    static void validate(int sal)throws Exception{

    Exception e=new Exception("Salary out of Range");if(sal15000)

    throw e;

    }public static void main(String arg[]){

    int sal=Integer.parseInt(arg[0]);try{

    validate(sal);}catch(Exception e){

    System.out.println(e.getMessage());}finally{

    System.out.println("Salary="+sal);}

    }}

    User Defined ExceptionsAlthough Java s built-in exceptions handle most common errors,you will probablywant to create your own exception types to handle situations specific to yourapplications. This is quite easy to do:just define a subclass ofException (which is,ofcourse,a subclass ofThrowable ).Your subclasses don t need to actually implementanything it is their existence in the type system that allows you to use them asexceptions.

  • 8/14/2019 Core Java Index

    44/46

    Following program demonstrates how to create user-defined exceptions in java

    class StringNotMatchException extends Exception{

    StringNotMatchException(String str){

    super(str);}

    }class UserDefined{

    public static void main(String args[]){

    String s1,s2;s1=args[0];s2=args[1];StringNotMatchException se=new StringNotMatchException("Strings

    are not equal");

    try{

    if(!s1.equals(s2))throw se;

    }catch(StringNotMatchException ste)

    { System.out.println(ste.getMessage());}finally{

    System.out.println("First string is="+s1);System.out.println("Second string is="+s2);

    }}

    }

  • 8/14/2019 Core Java Index

    45/46

    Question Bank

    1. What is the exception? Explain the need of ExceptionHandling in java.2. Explain Common Exceptions classes defined by java.

    3. Explain trycatch finally construct.4. Explain throw and throws keyword.5. Differntaite throw and throws keyword.6. Explain the need of user defined exceptionsin java? How they are created.

  • 8/14/2019 Core Java Index

    46/46

    Students Name:

    -_________________________________________________________

    College: -

    _________________________________________________________

    CORE JAVA AND PRGRAMMING