Java Notes-bsk (1)

download Java Notes-bsk (1)

of 85

Transcript of Java Notes-bsk (1)

  • 8/3/2019 Java Notes-bsk (1)

    1/85

    UNIT - I

    Introduction:Programming Languages are classified into the following categories

    A)Monolytic Programming Languages B)Procedural Programming LanguagesC)Structured Programming Languages D)Object Oriented Programming Languages

    a) Monolytic Programming Languages: Monolytic Programming Languages contain number of lines ofdata.

    Drawback: 1. It is not subroutine concept.2. The program code is duplicated each time it is to be used.

    Examples: Assembly Language, Basicb) Procedural Programming Languages: The important features of Procedural Programming Languagesare

    i) Emphasis on algorithm rather than dataii) Programs are organized in form of subroutineiii) Program controls are through jumps (goto) and calls to subroutineiv) Data move overly around the system from function to functionv) It follows top down approach in program designvi) It is suitable for medium size software applications

    Drawback: 1. Data Security problem2. Difficult to maintain program code3. It doesnt model to real world problem very well

    Examples: Fortran, Cobolc) Structured Programming Languages: In Structured Programming Languages programs consist ofmultiple modules and each module has a set of functions of related types. The important features ofStructured Programming Languages are

    i) Programs are divided into individual procedures that performs discrete tasksii) Procedures are independent of each otheriii) Procedures have their own local data and processing logic

    iv) Introduction of the concepts of user defined datatypesv) Maintenance of a large software system costly

    Sub programming

    Module 1 Module 2Drawback: 1. Data Security problem

    2. It doesnt model real world problem very well

    1

    1 ----2 -------

    ---

    Global data

    Global data

  • 8/3/2019 Java Notes-bsk (1)

    2/85

    Examples: Pascal, Cd) Object Oriented Programming Languages: The important features of Object Oriented ProgrammingLanguages are

    i) Emphasis on data rather than functionsii) Programs are divided into objectsiii) Functions that operate on the data of an object are together in the data structureiv) Data is hidden and cannot be accessed by external functions (Data security)v) Objects may communicate with each other through functions

    vi) New data can be easily added to the functions whenever necessaryvii) It follows bottom-up approach in program designing

    Object A Object B

    Object CThe important features of Object Oriented Programming are

    a) Encapsulation b)Abstraction c)Inheritance d)Polymorphisma) Encapsulation: The mechanism by which the data and functions are bounded together with an objectdefinition. By means of Encapsulation, it can possible to protect the data.b) Abstraction: It is the process of defining data type often called an abstract data type together with the

    principle of data hiding.Abstract Data type refers to the program defined data type together with a set of operations than

    can be performed on the data. Data hidingis a property where by the internal data structure of an object ishidden from the rest of the program. The data can be accessed only by the function declared with in theclass.

    c) Inheritance: Inheritance is the mechanism that allows the programmer to derive new classes fromexisting classes. The derived classes inherit the methods and data of the parent class.d) Polymorphism: Polymorphism is a feature that allows giving a single name to different methods withdifferent parameters. Depending on the parameters only one particular method is executed.Object Based Programming = Data Encapsulation + Data Hiding + Overloading (Polymorphism)

    Example: AdaDynamic Binding: When a method is called within a program, it associated with the program at run timerather than at compile time is called dynamic binding.Object Oriented Programming = Object Based Programming Concepts + Inheritance + Dynamic

    Binding (Polymorphism)

    Example: C++, JAVA

    Advantages of OOP1. OOP uses objects in programming languages.2. The independence of each object easily to development and maintenance of the program

    2

    Data

    functions

    Data

    functions

    Data

    functions

  • 8/3/2019 Java Notes-bsk (1)

    3/85

    3. Data Hiding and Data Abstraction increase reliability and helps the programmer to built secureprograms.

    4. Dynamic Binding increases flexibility by permitting the addition of new class objects withouthaving to modify the existing code.

    5. Inheritance with Dynamic Binding enhances asthe reusability of code.

    Applications of OOP1)Simulation and Modeling 2)User Interface Design 3)Artificial Intelligence and Expert Systems4)Neural Networks 5)Web Designing 6)CAD/CAM System

    JAVA: Java Programming Language was designed by James Gosling at Sun Microsystems in 1991.This language was initially called Oak but was renamed Java in 1995. It follows both the features of Cand C++.

    Java Programming Language was very useful on Internet Programming. Since, by this languagewe can easily transfer the information from server to the nodes through the network. It provides active

    programs when we are viewing the passive data and self-executing programs. Generally, in the case ofnetwork programs Security and Portability is the main active areas concern. The Java AppletProgramming provides such things.

    Java programs are classified into 2 types. 1) Application Programs 2) Applet ProgramsAn Application is a program run on the computer under the operating system of the computer. This

    is similar to the other programming languages.

    An Applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser.

    Java Features/Buzz Wordsa) Platform Independent: Java is a platform independent language. Once we create the program in oneoperating system, the program is worked in any operating system that is transmitted to the operatingsystem.b) Portable: The most significant contribution of Java over other languages is its portability. Java

    programs can be easily moved from one computer system to another anywhere and any time. Changes andupgrades in operating systems, processors, system resources will not forces any changes in Java

    programming.

    c) Object oriented: Java is a true object oriented language. Why because without class we cant run theprogram. Without main we can run the program. Almost everything in Java is an object. All programcode & data reside with objects and classes. The object model in Java is simple and easy.d) Robust & Secure: Java is a Robust Language. It provides many safe guards to ensure reliable code. Itis designed as garbage collected language relieving the programmers, virtually all memory management

    problems. Java also incorporates the concept of exception handling, which captures serious errors andeliminates any risk on crashing the system.

    Security becomes an important issue for a language that is used for programming on Internet. Javasystems not only verify all memory access but also ensure that no viruses are communicated with theApplet.e) Distributed: Java is designed as a distributed language for creating applications on network. It has the

    ability to share both data and program. Java applications can open and remote object on Internet as easilyas they can do in local system.f) Simple & Small: Java is a simple & small language. Many features of C and C++ that are sources areunreliable code are not part of Java. For example, Java doesnt use Pointers, Preprocessors, Header files,goto statements and many others.g) Multi Threaded: Java was designed to meet the real-world requirement of creating interactive,networked programs. Java supports multithreaded programming, which allows to handling multi taskssimultaneously. This means we need not wait for the application to finish one task before beginninganother one.h) Dynamic: Java is a dynamic language. Java is capable on dynamically linking in new class, libraries,methods and objects. Java support functions written in other languages such as C and C++. These

    functions are known as native methods. Native methods are linked dynamically at run time.i) Compile & Interpreted: Usually a Computer language is either compiled or interpreted. Javacombined both these approaches thus making. Java is a two-stage system. First Java Compiler translates

    3

  • 8/3/2019 Java Notes-bsk (1)

    4/85

    source code into byte code instruction and therefore in the second stage Java Interpreter generates machinecode that can be directly executed by the machine that is running the Java program.Interpreter is called JVM (Java Virtual Machine). Java applications are platform independent. JVM, JDKare platform dependent. Interpreter is different for all operating systems like DOS, UNIX etc.,The main drawback of C is the program cannot run in any other operating system. It is advantage of Java.

    j) High performance: Java performance is impressing for an interpreted language due to the use ofintermediate code. Java architecture is also design to reduce overheads during runtime. The incorporationof multithreading enhances, the overall executions, speed of Java programs.

    BASICS OF JAVA ENVIRONMENT:

    Phase 1

    Phase 2 Primary Memory

    Phase 3

    Phase 4 Primary Memory

    Phase 5 Primary Memory

    Phase 1: Java program is typed in a text editor (Notepad, Edit plus) and makes corrections if necessary.The programmer specifies that the file in the editor should be save. The program is stored on a secondstorage device such as a disk. Java program files are stored with .java extension filenames.

    Save: c:\jdk1.2.1\bin\filename.javaPhase 2: The programmer gives the command javac filename.java to compile the program. At this stage,the Java compiler translates the Java program into byte code that is the language understood by the JavaInterpreter. If the program compiles correctly, a file called filename.class is produced. This is the filecontaining byte codes that will interpret during the execution phase.Phase 3: This phase is called loading. The program must place in memory before it can be executed. This

    is done by the class loader, which takes the .class file containing in byte code and translates it into thememory. The .class file can be loaded from a disk on your system or over a network.Phase 4: Byte code verifier confirms that all byte codes are valid and dont valid Java SecurityInstructions.Phase 5: Java Interpreter reads byte code and translates them into a language that the computer canunderstand and it executes the code.Java Development Kit: Java Development Kit is a collection of classes, Java compiler and Java virtualmachine Interpreter. It also consist useful utilities for debugging, documentation, compiling and run java

    programs.The following are the some components of a Java Development Kit.

    javac: The java compiler, converts java source code into byte codeSyntax: javac filename.java

    java: The java interpreter, executes java application byte does directly from class fileSyntax: java filename

    4

    Editor disk

    Compiler disk

    disk

    Class loader

    Byte code verifier

    Interpreter

  • 8/3/2019 Java Notes-bsk (1)

    5/85

    jdb: The java debugger that allows to step through the program one line at a time, set break points,and examine variables

    Syntax: jdb filename

    servletrunner: A simple web server to test servlets

    appletviewer: A java interpreter that executes java applet classes hosted by HTMLSyntax: appletviewer filename.html

    Java Virtual Machine (JVM): Java provides both compiler and a software machine called JVM for eachcomputer machine. The Java Compiler translates the Java Source Code (Java program) into an

    intermediate code known as byte code, which executes on special type of machine. This machine is calledJava Virtual Machine and exists only inside the computer memory. The byte code is machine independentcode and can run in any system.

    The byte code is not a machine specific code. Java Interpreter takes the byte code and translates it into itsown system machine language and runs the results.

    Just In Time (JIT): The Java Virtual Machine is an interpreter that translates and runs each byte codeinstruction separately whenever it is needed by the computer program. In some cases it is very slow.

    As an alternative, Java also provides local compiler for each system that will compile byte code file

    into executable code for faster running. Java calls these compilers Just In Time compilers.Java Standard Library(JSL): The Java API (Application Programming Interface) is a collection ofclasses and methods grouped in the form of packages. JDK 1.2 has 58 packages, it is also known as JavaStandard Library.

    The important Packages in Java area) java.lang: It contains the main language support class. It contains wrappers, strings and basic features ofJava

    b) java.util: It provides classes that support date, time, basic event processing etc.,c) java.io: It provides reading and writing data in the form of streams.d) java.awt: It provides classes for creating GUI programs.e) java.applet: It includes set of classes to support for applet programming.f) javax.swing: It provides classes for swing operation programming.Differences between C++ and Java

    1. Java does not include structure and union.2. It is not possible to declare unsigned integer in Java.3. Pointers dont exist in Java.4. Java does not have a preprocessor.5. There are no header files and delete operators.6. Java does not allow goto, sizeof and typedef.7. Java does not support the multiple inheritance.

    Java Tokens: Tokens are smallest individual units in a program. The compiler reads the source program

    one character at a time grouping the source program into a sequence of atomic units called Tokens.Reserved words, identifiers, constants, operators etc., are the examples of Java Tokens.

    Keywords:The Keywords or Reserved words are one, which have a special and predefined meaning tothe Java compiler. There are 48 reserved words currently used in Java. These words cannot be used asnames for a variable, constant, class or method. Reserved words areabstract boolean break byte case catchchar class const continue default dodouble else extends final finally floatfor goto if implements import instanceof int interface long native new package

    private protected public return short static

    strictfp super switch synchronized this throwthrows transient try void volatile whiletrue false null

    5

    Source code Java Compiler Byte code

    Byte codeJava Interpreter Machine code

  • 8/3/2019 Java Notes-bsk (1)

    6/85

    Note: const and goto are reserved for future use. Java reserved words true, false and null reserved wordsare used to represent the values.

    Datatype: Datatypes are used to specify the type of data that a variable can attain. There are 2 types ofdatatypes. 1. Primitive Datatypes 2. Non-Primitive Datatypes1. Primitive Datatype: It is also called as standard, intrinsic or built-in datatypes. There are eight primitivedatatypes available in Java. Those are byte, short, int, long, char, float, double and boolean. These can beclassified into four groups.

    Integers : byte, short, int, long

    Floating point numbers : float, doubleCharacters : char Boolean : booleanType Size Range

    Bits Bytesint 32 4 -2,147,483,648 to 2,147,483,647long 64 8 -9,223,372,036,854,775,808 to

    9,223,372,036,854,775,807short 16 2 -32,768 to 32,767

    byte 8 1 -128 to 127float 32 4 3.4 e 0.38 to 3.4 e +0.38

    double 64 8 1.7 e 308 to 1.7 e +308char 16 2 0 to 65535

    boolean 8 1 true / falseNote: 1. Java does not support have any unsigned types

    2. Variables of types char, byte, short, int, long, float and double are all given the value 0 bydefault3. Variable of type boolean are given false by default4. All primitive datatypes in Java are portable (Platform independent)

    2. Non-Primitive Datatype: These are also known as Derived Datatype or Abstract Datatype or Referencetype. These are built on primitive data types.Examples: string, class, array, interface etc.,

    Variable: The name given to the various elements to store the information is called an identifier orvariable. The rules for variables are as follows:

    Variable must be begin with a letter, a dollar ($) symbol or an underscore ( _ ) followed by asequence of letters

    Variable names must be unique

    There should be no space in between any two characters of an identifiers

    Keywords cannot be used for variable name

    Java is a case-sensitive, so upper and lower case letters are distinctDeclaring a Variable: All variables must be declared before they can be used. The basic form of avariable declaration is Syntax: type identifier;

    Where type is represents datatype of the variable, identifier is the name of the variable.Example: int a;

    More than one variable of the same type can be declared by using a comma-separated list.Syntax: type identifier1, identifier2, , identifiern;Example: float x, y, z;

    Initializing a Variable: Variable can also be initialized with equal sign and a value.Syntax: type identifier = value;Example: int a = 3;

    Dynamic Initialization: Java allows variables to be initialized dynamically, using any expression validat a time the variable is declared.

    Example: class dyna{

    public static void main(String args[])

    6

  • 8/3/2019 Java Notes-bsk (1)

    7/85

    { double a=3.0, b=4.0; double c=Math.sqrt(a*a+b*b);System.out.println(Hypotenuse is + c);

    } }Scope & Lift-time of a Variable:

    An identifier duration also called lifetime is the period during which that identifier exist in memory.Identifier that represent local variables in a method i.e., parameters and variables declared in the method

    body have automatic duration. Automatic declaration are created when program control reaches theirdeclaration they exist while the block in which they are declare is active and they are destroyed when the

    block in which they are declared is exceeded. We will refer to variables of automatic duration hasautomatic variables or local variables.

    Java also has identifiers of static duration. Variables and references of static duration exist fromthe point at which the class that defines them is loaded into memory for execution until the programtermination.

    Identifier scope is where the identifier can be a reference in a program. The scope of an identifieris class scope and block scope.

    Methods and instance variable of a class have class scope. Class scope begins at the beginning leftbrace of the class definition and ends at the closing right brace of the class definition.

    Identifiers declared inside a block have block scope. Block scope begins at the identifiersdeclaration and ends at the terminating right brace of the block. Local variables of the method have block

    scope.Class: A class is a non-primitive datatype that contains member variables (data) and member functions(methods) that operates on the variables. A class is declared by the use of the class keyword. The generalform of class definition is as follows.

    Syntax: class class-name{

    datatype instance-variable1;datatype instance-variable2;-datatype instance-variablen;datatype methodname1(parameter-list){// method body}-datatype methodnamem(parameter-list){// method body}

    }The data, or variables defined with in a class are called instance variables. The code is present with

    in methods. Collection of methods and variables defined with in a class are called members of the class.Example: class box{double width, height, depth;double volume( ){return width*height*depth;}}

    Object: Object is an instance of the class. By means of the object only, we can access the functions(methods).

    7

  • 8/3/2019 Java Notes-bsk (1)

    8/85

    main( ){

    box a = new box( );a.volume();}

    Comments in a Program: Three types of comment statements are available in Java. They arei) Single line comment (//)ii) Multi line comment (/* and */)

    iii) Documentation comment (/** and */)1. Single line comment: For a single line comment we use double slash (//) to begin a comment. It ends atthe end of line.

    Example: // Program for stack operations2. Multi line comment: For more than one line of information, we use multi line comments. Multi linecomments are starts with /* and ends with */.

    Example: /* Program for stack operationsDesigned by shabbirPBRVITS, Kavali */

    3. Documentation comment: For the documentation purpose, we use documentation comments.Documentation comments are starts with /** and ends with */.

    Example: /** A test for JDK

    Input and Output Statements: java.lang package consists a class called System which containsconsole I/O methods. If we want to take the information from the keyboard and display the information onthe screen, Java uses Stream objects. The system provides three basic streams. Those are

    a) System.in b)System.out c)System.err System.in refers to the standard input stream, System.out refers to the standard output stream andSystem.err refers to the standard error stream.System.out class consists of two methods to print the strings and values on the screen. They are 1. print( )2. println( ).1. print( ): Syntax: System.out.print(list);

    This statement prints the values of the variable name specified in the list of output unit.Example: System.out.print(hai);

    System.out.print(java);O/P: haijava

    2. println( ): Syntax: System.out.println(list);This statement prints the values of the variable name in the list, the cursor is advanced by one line

    and the next statement is print in the next line.Example: System.out.print(hai);

    System.out.print(java);O/P: hai

    javaNote: Java has a version of the + operator for string concatenation that enables a string and a value ofanother datatype.

    Example: sum = 50sum is + sum

    Here, sum is automatically converted to a string and concatenated with the sum is which resultsin the string sum is 50

    Example: y#2=+7O/P: y#2=7

    Command Line Arguments: Java has the facility of command line arguments. Java main methodconsists array of string objects. When we run the program, the array will fill with the values of any

    arguments it was given in the command line.Building the Java Program:

    8

  • 8/3/2019 Java Notes-bsk (1)

    9/85

    Java is a text file that contains one or more class definitions. Java compiler requires that a sourcefile use the .java file name extension.

    Example: class Example{

    public static void main(String[] args)

    {

    System.out.println("Hello");

    }

    } The keyword class is used to declare the new class is being defined

    Example is an identifier that is the name of the class

    Entire class definition will be between the opening curly brace ({) and the closing curly brace (})

    public keyword is an access specifier, which allows the programmer to control the visibility ofclass members

    The keyword static allows main() to be called without having to instantiate a particular instanceof the class. Since, main() method is called by the Java interpreter before any objects are made

    The keyword void used to tell the compiler that main() does not return a value

    main() is a method called when a Java application begins

    String args[] declares a parameter named args, which is an array of instances of the class string.args receives any command line arguments present when the program is executedNow the file is saved with .java extension . Let the file name is taken as Example.java

    Compiling & Running the Java Program:To compile Example.java program by the compiler javac, specify the name of the source file on the

    command line asC:\> javac Example.javaHere, the Java compiler creates a file called Example.class that contain byte code version of the

    program. The class file is run by the Java interpreter, called java by passing the name to command lineargument as

    C:\> java Example

    O/P: HelloExample: Write a program to read two values and print the valuesclass ex2

    { public static void main(String[] args)

    { System.out.println(args[0]); System.out.println(args[1]);

    }}

    Primitive datatypes are to be converted into object type by using the wrapper classes. Integer class is usedas wrapper class for primitive datatype int. parseInt( ) method converts string to an int.Example: Write a program to read two integer values and print the sumclass ex3

    {

    public static void main(String[] args)

    {

    int a,b,sum;

    a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]);

    sum=a+b;

    System.out.println("sum of a and b is"+sum);

    }

    }

    OPERATORSOperator is a symbol that performs a specified operation between the data items. Java provides the

    following different types of operators.a) Arithmetic operators: Operator Meaning

    9

  • 8/3/2019 Java Notes-bsk (1)

    10/85

    + Addition

    - Subtraction* Multiplication

    / Division

    % Modulus

    Example:class arope

    {

    public static void main(String[] args){

    int a,b,sum,sub,mul,div,mod;

    a=Integer.parseInt(args[0]);

    b=Integer.parseInt(args[1]);

    sum=a+b;

    sub=a-b;

    mul=a*b;

    div=a/b;

    mod=a%b;

    System.out.println("Addition="+sum);

    System.out.println("Subtraction="+sub);System.out.println("Multiplication="+mul);

    System.out.println("Division="+div);

    System.out.println("Remainder="+mod);

    }

    }

    b) Arithmetic Assignment Operators:

    Syntax: variable operator = expressionWhich is equivalent to

    variable = variable operator expression

    Operator Example Equivalent Expression

    + = a + = 4 a = a + 4

    - = a - = 5 a = a 5

    * = a * = 3 a = a * 3

    / = a / = 8 a = a / 8

    % = a % = 5 a = a % 5

    c) Assignment Operator: = is an assignment operator used to assign the value to a variable.Syntax: variable = value;Example: a = 7;

    d)Increment and Decrement Operators: ++ and --' are Javas increment and decrement operators. The

    increment operator increased its operand by one. The decrement operator decreased its operand by one.Example:class a

    { public static void main(String[] args)

    {

    int x=4;

    System.out.println("x++:"+ ++x); //O/P: 5

    int y=10;

    System.out.println("x++:"+ y++); //O/P: 5

    int p=5;

    int t=--p+3;

    System.out.println("t :"+t); //O/P: 7}

    }

    e) Relational Operators: Relational Operators determines the relationship between the two operands.

    10

  • 8/3/2019 Java Notes-bsk (1)

    11/85

    Operator Meaning Example= = equal to A= =B!= Not equal to A!=B

    > Greater than A>B

    < Less than A= Greater than or equal to A>=B

    > Shift right

    >= Shift right Assignment

  • 8/3/2019 Java Notes-bsk (1)

    12/85

    javax.swing:It is package contains an important class called JOptionPane class. This class is used todisplay dialog boxes. It provides two important predefined methods showInputDialog andshowMessageDialog called static methods. Such methods are always used their class name followed by adot operator.ShowInputDialog: showInputDialog is a method of class JOptionPane. It is a static method and thegeneral format is as

    Syntax: JOptionPane.showInputDialog(argument);

    The argument indicates to the user what to do in the text field.

    Example: JOptionPane.showInputDialog(Enter a value);When we perform this operation the input dialog box is available as

    The users types characters in the text field then clicks the ok button, it returns string to the program.showMessageDialog: showMessageDialog is method of class JOptionPane. It is a static method. The

    general format of showMessageDialog is in two ways.Syntax1: JOptionPane.showMessageDialog(null,argument1);The first argument must be null keyword. The second argument is the string that is required to display.The title bar of message dialog contains the string Message to indicate that the dialog is presenting amessage to the user. The default icon is INFORMATION_MESSAGE.

    Example: JOptionPane.showMessageDialog(null,value=+x);

    Syntax2: JOptionPane.showMessageDialog(null,argument2,argument3,argument4)

    The first argument must be null keyword. The second argument is the message to display. The thirdargument is the string to display in the title bar of the dialog. The fourth argument is a valueindicating the type of message dialog to display.

    For argument4 some of the message dialogs areJOptionPane.PLAN_MESSAGEJOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGE

    Example:JOptionPane.showMessageDialog(null,value=+x,output,

    JOptionPane.ERROR_MESSAGE)

    import statement: import statement is similar to the #include statement in C. Using the importstatements, we can access to classes that are part of other packages.

    Example: import javax.swing.JOptionPane;This statement instructs that the interpreter to load the JOptionPane class contained in the javax.swing

    package.Example:import javax.swing.JOptionPane;

    class ch

    12

    Input

    Enter a value?

    OK cancel

    Message

    Value=10iOK

    output

    Value=10OK

  • 8/3/2019 Java Notes-bsk (1)

    13/85

    {

    public static void main(String[] args)

    {

    String sn1;

    int x;

    sn1=JOptionPane.showInputDialog("Enter x value");

    x=Integer.parseInt(sn1);

    JOptionPane.showMessageDialog(null,"value="+x,"output",JOptionPane.ERROR_MESSAGE);

    }}Control Statements

    Depending on the results of computations the flow of control may require to jump from one part ofthe program to another part, such jumps are called Control statements. The control statements are of twocategories.1)Decision (Conditional) control statements 2)Loop control statements 3)Jump control statements1. Decision (Condition) Control statements: In decision control statements, depending on the result ofevaluation of an expression a statement or block of statements are executed. The condition involves

    boolean values either true or false. Java provides the following decision control statements.a)if statement b)if-else statement c)nested if-else statement d)switch

    a) if statement: The if statement conditionally process the statements when the specified test condition is

    true.Syntax: if(condition)

    {// Block of statements

    }Flowchart:

    Here, if the condition is true then block of statements are executed. Otherwise, block of statementsare not executed and the control is passed to the next statements available after the block statements.

    The statements are either simple or compound statements. If the statements are single statementthen they ended with a semicolon. If the statements are compound statements then they are placed in

    between the left and right curly braces.Example:

    class if1{

    public static void main(String[] args)

    {

    int a=6,b=4;

    if(a>b)

    System.out.println("a is big"); }}

    b) if-else statement: In if-else statement general form is asSyntax: if (condition)

    {//true block statements

    }else{

    //false block statements

    13

    Condition

    Block of statements

    Next statements

  • 8/3/2019 Java Notes-bsk (1)

    14/85

    }

    Flowchart:

    Here, first the test condition is evaluated. If the condition is true, then true block statements areexecuted otherwise false block statements are executed.

    The statements are either simple or compound statements. If the statements are single statementthen they ended with a semicolon. If the statements are compound statements then they are placed in

    between the left and right curly braces.Example:class if2

    {

    public static void main(String[] args)

    {

    int a=2,b=4;

    if(a>b)

    System.out.println("a is big");

    else

    System.out.println("b is big");

    }}

    c) Nested if-else statement: The if-else statement is placed within another if-else statement such methodsare called nested if-else statement.

    Syntax: if (condition1){else if(condition2){

    //block1 statements}else

    {//block2 statements

    }}else{ //block3 statements }

    Lab Program1: Write a program to print the roots of a quadratic equation ax2+bx+c=0import javax.swing.JOptionPane;

    import java.text.DecimalFormat;

    class lab1

    {

    public static void main(String[] args)

    {

    double a,b,c,dis,root1,root2,p;

    14

    Condition

    true blockstatements

    Next statements

    false blockstatements

  • 8/3/2019 Java Notes-bsk (1)

    15/85

    DecimalFormat d=new DecimalFormat("0.00");

    a=Double.parseDouble(JOptionPane.showInputDialog("Enter a value"));

    b=Double.parseDouble(JOptionPane.showInputDialog("Enter b value"));

    c=Double.parseDouble(JOptionPane.showInputDialog("Enter c value"));

    dis=(b*b-4*a*c);

    if(dis==0)

    {

    System.out.println("Roots are real and equal");

    root1=-b/(2*a);System.out.println("Root1="+(d.format(root1)));

    System.out.println("Root2="+(d.format(root1)));

    }

    else if(dis>0)

    {

    System.out.println("Roots are real and different");

    p=Math.sqrt(dis);

    root1=(-b+p)/(2*a);

    root2=(-b-p)/(2*a);

    System.out.println("Root1="+(d.format(root1)));

    System.out.println("Root2="+(d.format(root2)));}

    else

    System.out.println("Roots are imaginary");

    }

    }

    d)switch statement: The switch statement allows section among the multiple section of a code dependingon the value of an expression. The objective is to check several possible constant values for an expression.

    Syntax: switch (expression){case value1: block1 statements

    break;case value2: block2 statements

    break;|default: default block statements}

    Flowchart:

    First, the switch statement evaluates the expression and check whether the evaluated value iscoinciding with any case value or not. If any value is coinciding, it executes that particular block ofstatements until the break statement is reached. After executing the statements the control is transferredout of the statements that are available after the switch statement.

    If any value is not coinciding with the case value then it executes default block statements. Default

    block is an optional.Note: case values are either integer constant or character constant.Example:

    15

    expression

    block1statements

    Block2statements

    defaultblock1statements

    Next statements

  • 8/3/2019 Java Notes-bsk (1)

    16/85

    class if4

    {

    public static void main(String[] args)

    {

    int rno;

    rno=Integer.parseInt(args[0]);

    switch(rno)

    {

    case 1:System.out.println("RED");break;

    case 2:System.out.println("GREEN");

    break;

    case 3:System.out.println("BLUE");

    break;

    default:System.out.println("Select 1,2 or 3 only");

    }

    }

    }

    Example:

    class if5{

    public static void main(String[] args)

    { char rno='t';

    switch(rno)

    {

    case 'a':System.out.println("RED"); break;

    case 'b':System.out.println("GREEN"); break;

    case 'c':System.out.println("BLUE"); break;

    default:System.out.println("Select 1,2 or 3 only");

    }

    }

    }

    2. Loop Control Statements: A Loop statement allows to run a statement or block of statementsrepeatedly for a certain number of times. The repetition is continues while the condition is true. When thecondition becomes false, then loop ends and control passed to the next statements following the loop.Repetitive execution of statements is called looping. Java provides three types of loop control statements.

    a) while statementb) do-while statementc) for statement

    a) while statement: while loop executes the statements repeatedly as long as a given condition becomes

    true. When the condition becomes false the control immediately pass to the next statements available afterthe loop statements.Syntax: while (condition)

    {//statements

    }Flowchart:

    16

    condition

    statements Nextstatements

  • 8/3/2019 Java Notes-bsk (1)

    17/85

    The statements are either simple or compound statements. If the statements are single statementthen they ended with a semicolon. If the statements are compound statements then they are placed in

    between the left and right curly braces.Lab Program2: Write a program to print the first n fibonacci sequence numbersclass lab2

    {

    public static void main(String[] args)

    {int f0=1,f1=1,i=3,f2,n;

    n=Integer.parseInt(args[0]);

    System.out.println(f0);

    System.out.println(f1);

    while(i

  • 8/3/2019 Java Notes-bsk (1)

    18/85

    do

    {

    x=n%10;

    sum=sum+x*x*x;

    n=n/10;

    }while(n>0);

    if(sum==temp)

    System.out.println("Number is armstrong");

    elseSystem.out.println("Number is not armstrong");

    }

    }

    c) for statement: The for statement also repeat a statement or compound statements for a specified numberof times. The general form of for statement is as

    Syntax: for (initialization;condition;increment/decrement){

    //statements}

    Flowchart:

    Initialization is the start with the assigning value to the variable and it executes only once at the start of theloop. Then the control checks for the test condition.

    In condition section, if the condition becomes true then the control pass to the block of statementsand executed. After executing the statements the control pass to the increment/decrement section. Afterincrementing/decrementing the variable again the control is passed to the condition section. This

    procedure is repeated as long as the condition becomes true.If the condition becomes false, the control passes out of the loop statements.

    Note: 1. Multiple initializations are possible by comma operator.Ex: for( i = 0,j = 5; i

  • 8/3/2019 Java Notes-bsk (1)

    19/85

    count=1; break;

    }

    j++;

    }

    if(count==0)

    System.out.println(x+"is prime");

    }

    }

    }3. Jump Control Statements: Java provides the following Jump Control statements.

    a) break statement b)continue statement c)return statement d)exit statementa) break statement: break statement executed in a while, do-while, for or switch statements causesimmediate exist from that structure. It can be used in two ways as unlabeled break and labeled breakstatement.Unlabeled break statement:

    Syntax: break;Example: for(int k=1;k

  • 8/3/2019 Java Notes-bsk (1)

    20/85

    continue;

    System.out.println(k);

    }

    O/P: 1 2 3 4 6 7 8 9 10Labeled continue statement: The labeled continue statement when executed in a repetition structure skipsthe remaining statements in that structure body and any number of enclosing repetition on structure and

    proceeds with the next iteration of an enclosed labeled repetition.Example:

    class ex{

    public static void main(String[] args)

    {

    stop:

    for(int row=1;row

  • 8/3/2019 Java Notes-bsk (1)

    21/85

    Syntax: type arrayname[]={list of values};Where, list of values contains number of values separated by commas and surrounded by curly braces

    Example: type number[]={35,40,56,23};In Java, all arrays store the allocated size in a variable named length. We can access the length of

    the array using the syntaxSyntax: arrayname.length;

    Example 1: Write a program to read 5 numbers and print the sum of it.class arr1

    {public static void main(String[] args)

    {

    int sum=0; int no[]=new int[10];

    for(int i=0;i

  • 8/3/2019 Java Notes-bsk (1)

    22/85

    It can also be initialize arrays automatically when they are declared. The syntax is asSyntax: type arrayname[][]={list of values};

    Or

    type arrayname[][]={{row1 values},

    {row2 values},

    .. }

    Lab Program 6: Java program to multiply two matrices

    import javax.swing.JOptionPane;class arr2

    { public static void main(String[] args)

    { int m,n,p,q,i,j,k;

    int a[][]=new int [10][10];

    int b[][]=new int [10][10];

    int c[][]=new int [10][10];

    m=Integer.parseInt(JOptionPane.showInputDialog("Enter rows of Matrix A"));

    n=Integer.parseInt(JOptionPane.showInputDialog("Enter columns of Matrix A"));

    p=Integer.parseInt(JOptionPane.showInputDialog("Enter rows of Matrix B"));

    q=Integer.parseInt(JOptionPane.showInputDialog("Enter columns of Matrix B"));

    if(n==p){ for(i=0;i

  • 8/3/2019 Java Notes-bsk (1)

    23/85

    is of the higher type. Such type of casting is called Implicit Type Casting. In Implicit Type Casting thereis no loss of data. The following are some of implicit type castings with no loss of data

    from tobyte short, char, int, long, float, doubleshort char, int, long, float, doublechar int, long, float, doubleint long, float, doublelong float, double

    float double2. Explicit Type Casting: If we want to force to convert the operands of an expression from one type toanother type depending on user choice, such type of casting is called Explicit Type Casting. In ExplicitType Casting there is a chance of data loss when we convert the operands from higher type to lower type.The process of converting the value is known as Casting a value. The general form of casting is as

    Syntax: (datatype) expression;Example: x = (int) 7.5;

    Note: The final result of an expression is converted to the type of the variable before assigning to the lefthand side variable. In such case following chances are introduced.

    float to int causes truncation of the fractional part

    double to float causes rounding of digits

    long to int causes dropping of the excess of higher order bits**

    Unit IIClass: A class is a non-primitive datatype that contains member variables (data) and member functions(methods) that operates on the variables. A class is declared by the use of the class keyword. The generalform of class definition is as follows.

    Syntax: class class-name{

    datatype instance-variable1;

    datatype instance-variable2;

    --

    datatype instance-variablen;

    datatype methodname1(parameter-list)

    {

    // method body

    }

    -

    -

    datatype methodnamem(parameter-list)

    {

    // method body

    }

    }

    The data, or variables defined with in a class are called instance variables. The code is present within methods. Collection of methods and variables defined with in a class are called members of the class.

    Example: class box{

    double width, height, depth;

    double volume( ){

    return width*height*depth;

    }

    23

  • 8/3/2019 Java Notes-bsk (1)

    24/85

    }

    Creating Objects: An Object in Java is a block of memory that contains space to store all the instancevariables. Creating an object of a class is a two-step process.

    1. Declare a variable of the class type. At this stage, the variable refers to an object only.2. Assigning an actual, physical copy of the object and assign it to that variable by means of new

    operator. The new operator dynamically allocates memory for an object and returns a referenceto that object.

    Example: Rectangle rect1; // referencerect1 = new Rectangle(); // instantiate

    (or)

    Rectangle rect1 = new Rectangle();

    The first statement declares a variable to hold the object reference.

    rect1The second statement assigns the object reference and allocates memory

    rect1

    Note: Each object contains its own instance variables of its class. This means that any changes to thevariables of one object have no effect on the variables of another. But the function name is name for bothobjects.

    It is also possible to create two or more references to the same object.Example: Rectangle r1 = new Rectangle( );

    Rectangle r2 = r1;

    r1

    r2Methods: Methods allows the programmer to modularize a program. All variables declared in methoddefinition are local variables and method parameters are also local variables. All methods must defineinside a class definition. The general form of a method is as

    Syntax: type method-name (parameter-list){

    // body of the method

    }

    where,

    type specifies the type of data returned by the method. If the method does not return any value, its

    return type must be void The method-name is a valid identifier

    parameter-list is a sequence of type and identifier pairs separated by commas. The variablereceives the value of the arguments passed to the method when it is called. If the method has no

    parameters, then the parameter list will be empty

    body of the method describes the operations to be performed on the data

    Example: int sum(int a, int b){

    int c;

    c=a+b;return c;

    }

    24

    null

    Rectangleobject

    Rectangleobject

  • 8/3/2019 Java Notes-bsk (1)

    25/85

    Accessing class members: All variables must be assigned values before they are used in ourprogram. All class members are accessed by means of dot operator.The general format of accessing instance variable of the class by dot operator is as

    Syntax: objectname.variablename;Where, objectname is name of the object, variablename is the name of the instance variable.

    Example: rect1.length=15;rect1.width=10;

    rect1.lengthrect1 rect1.width

    The general format of accessing instance methods of the class by dot operator is asSyntax: objectname.methodname(parameter-list);

    Where, objectname is name of the object, methodname is the name of the instance method that calls withthe object and paramerter-list is a list of actual values separated by commas.

    Example: void getdata(int x, int y){

    length=x; width=y;

    }

    rect1.getdata(10,20);// Write a program to calculate the area of a rectangle.class Rectangle

    {

    int length1,width1;

    void getdata(int x,int y)

    {

    length1=x;width1=y;

    }

    int calarea()

    {

    int area=length1*width1;return area;

    }

    }

    class prg

    {

    public static void main(String[] args)

    {

    int a,b;

    Rectangle rect1=new Rectangle();

    Rectangle rect2=new Rectangle();

    rect1.length1=15; rect1.width1=4;

    a=rect1.length1*rect1.width1;

    System.out.println("Area of Rectangle1="+a);

    rect2.getdata(2,3);

    b=rect2.calarea();

    System.out.println("Area of Rectangle2="+b);

    }

    }

    Method Overloading: In Java it is possible to define two or more methods within the same class that

    share the same name as long as these methods have different sets of parameters (Based on the number ofparameters, the types of the parameters and the order of the parameters). Then the methods are said to beoverloaded, and the process is referred as Method Overloading.

    25

    1510

  • 8/3/2019 Java Notes-bsk (1)

    26/85

    When the overload method is called the Java compiler selects the proper method by examine thenumber, type and order of the arguments in the call. Method Overloading is commonly used to createseveral methods with same name that perform fast accessing.

    Note: Two methods differ in only by return type will result in a syntax error.Example1:class overload

    {

    int square(int x)

    {return x*x;

    }

    double square(double x)

    {

    return x*x;

    }

    }

    class check

    {

    public static void main(String[] args)

    {overload r1=new overload();

    int k=r1.square(3);

    double p=r1.square(4.0);

    System.out.println("k value="+k);

    System.out.println("p value="+p);

    }

    }

    Example2:class overload1

    {

    int sum(int x)

    {

    return x+x;

    }

    int sum(int x,int y,int z)

    {

    return x+y+z;

    }

    }

    class check1

    { public static void main(String[] args)

    {

    overload1 r1=new overload1();

    int k=r1.sum(3,5,7);

    System.out.println("k value="+k);

    }

    }

    Constructors: A constructor is a special method of class, which is invoked automatically, whenever an

    object of a class is created. It has the same name as its class and resides similar to a method. Aconstructor has the following characteristics.

    It doesnt have any return type not even void

    The constructor can be declared as public

    26

  • 8/3/2019 Java Notes-bsk (1)

    27/85

    It can be overloaded

    It is normally used to initialize the member of the objectDifferent types of Constructors:

    1) Default Constructor: A constructor that accepts no parameters is called the default constructor. If noconstructors are defined for a class, the Java system automatically generates the default constructor.Example:class Time1

    {

    int hour,min,sec;public Time1()

    {

    hour=10; min=45; sec=23;

    }

    void printdata()

    {

    System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");

    }

    }

    class const1

    {public static void main(String[] args)

    {

    Time1 t=new Time1(); t.printdata();

    }

    }

    O/P: 10hours:45minutes:23seconds

    2) Parameterized Constructor: A constructor that takes arguments as parameters is called parameterizedconstructor. If any constructors are defined by a class with the parameters, Java will not create a defaultconstructor for the class.Example:class Time1

    {

    int hour,min,sec;

    public Time1(int h,int m,int s)

    {

    hour=h; min=m; sec=s;

    }

    void printdata()

    {

    System.out.println(hour+"hours:"+min+"minutes:"+sec+"seconds");

    }}

    class const2

    {

    public static void main(String[] args)

    {

    Time1 t=new Time1(10,9,4); t.printdata();

    }

    }

    O/P: 10hours:9minutes:4seconds

    Constructor Overloading: An interesting feature of the constructor is that a class can have multipleconstructors. This is called Constructor Overloading. All the constructors have the same name ascorresponding to the class name that they are differ only interms of their signature as number of argumentsor datatypes or order.

    27

  • 8/3/2019 Java Notes-bsk (1)

    28/85

    Example:class Time1

    {

    int hour,min,sec;

    public Time1()

    {

    hour=0; min=0; sec=0;

    }

    public Time1(int h){

    hour=h; min=0; sec=0;

    }

    public Time1(int h, int m)

    {

    hour=h; min=m; sec=0;

    }

    public Time1(int h,int m,int s)

    {

    hour=h; min=m; sec=s;

    }void printdata()

    {

    System.out.println(hour+"hours:"+min+"minute:"+sec+"sec");

    }

    }

    class const3

    {

    public static void main(String[] args)

    {

    Time1 t=new Time1();

    t.printdata();

    Time1 t1=new Time1(9);

    t1.printdata();

    Time1 t2=new Time1(7,8);

    t2.printdata();

    Time1 t3=new Time1(10,9,4);

    t3.printdata();

    }

    }

    Static Class Members:Generally each class contains instance variables and instance methods. Every

    time the class is instantiated, a new copy of each of them is created. They are accessed using the objectswith the dot operator.If we define a member that is common to all the objects and accessed without using a particular

    object i.e., the member belong to the class as a whole rather than the objects created from the class. Suchfacility can be possible by using static keyword.The members declared with the static keyword are called static members.Example: static int x;

    static int show(int x,int y);

    The important points about static class members are

    Static members can be accessible without the help of objects. It can be accessible by using thesyntax: classname.members;

    A static method can access only static members (data + method)

    28

  • 8/3/2019 Java Notes-bsk (1)

    29/85

    A static block will be executed first (before main). Static variables are initialized first

    A static member data store the same memory for all objects

    Static method cannot be referred to this or super in anyway.Example1:class static1

    {

    static int c=0;

    void increment()

    {c++;

    }

    void display()

    {

    System.out.println("Value="+c);

    }

    }

    class Mstatic

    {

    public static void main(String[] args)

    {

    static1 s=new static1();

    static1 s1=new static1();

    static1 s2=new static1();

    s.increment();

    s1.increment();

    s2.increment();

    s.display();

    s1.display();

    s2.display();

    }}

    O/P: value=3

    value=3

    value=3

    without static keyword

    s1 s2 s3

    with static keyword

    s1 s2 s3

    Example2:class static1

    {

    static int a=10;

    static int b=34;

    static void call()

    {

    System.out.println("Value1="+a);

    }}

    class Mstatic1{

    public static void main(String[] args)

    {

    29

    0 0 0

    0

  • 8/3/2019 Java Notes-bsk (1)

    30/85

    static1.call();

    System.out.println("Value2="+static1.b);

    }

    }

    O/P: Value1=10

    Value2=34

    Example3:class static2

    {static int a=10,b;

    static void method(int x)

    {

    System.out.println("x="+x);

    System.out.println("a="+a);

    System.out.println("b="+b);

    }

    static

    {

    System.out.println("static block");

    b=a*4;}

    }

    class Mstatic2

    {

    public static void main(String[] args)

    {

    static2.method(35);

    }

    }

    O/P: static block

    x=35

    a=10

    b=40

    Access Modifiers/Control:Java provides four types of Access Modifiers. They are public, protected, default and private.

    Access Location public protected friendly or default private

    Same class Y Y Y Y

    Sub class in same package Y Y Y N

    Other classes in same package Y Y Y Y

    Sub classes in other packages Y Y N N

    Non-sub classes in otherpackages

    Y N N N

    For good programming technique place member data as private and member functions as public.Example:class modi

    {

    private int k=6; void display()

    {

    System.out.println("k in display="+k);

    }

    }

    class ex{

    public static void main(String[] args)

    30

  • 8/3/2019 Java Notes-bsk (1)

    31/85

    {

    modi obj=new modi();

    obj.display();

    //System.out.println("k in main="+obj.k);

    //this statement provides error since private variable

    //can not be possible to access by other class

    }

    }

    this keyword: Java define this keyword, that can be used inside any method to refer the current object.this is always a reference to the object on which method was invoked. this reference is implicitly usedto refer to both the instance variables and methods of current object.Example 1:

    class Box

    {

    int len,dep,hei;

    Box(int len,int dep, int hei)

    {

    this.len=len;

    this.dep=dep;

    this.hei=hei;} int volume() {

    return len*dep*hei;

    }}

    class this1

    {

    public static void main(String[] args)

    {

    Box obj=new Box(1,2,3);

    int x=obj.volume();

    System.out.println("volume="+x);

    }}

    O/P: olume=6

    this reference is also used explicitly refer to the instance variables.Example 2:

    class Box

    {

    int len=10;

    void method()

    {

    int len=40;

    System.out.println("local value="+len);System.out.println("Instance value="+this.len);

    }

    }

    class this2

    {

    public static void main(String[] args) O/P: local value=40

    { Instance value=10

    Box obj=new Box();

    obj.method();

    }}

    Argument Passing: Arguments passed to a sub-routine (method) is falls into two categories. 1.Call by value

    2. Call by reference

    31

  • 8/3/2019 Java Notes-bsk (1)

    32/85

    1. Call by Value: Call by value copies the value of an argument into the formal parameter of the sub-routine. Therefore, if changes made to the parameter of the sub-routine have no effect on the argumentused to call it.Example:class Test

    {

    void meth(int i, int j)

    {

    i*=2; j/=2;}

    }

    class cbv

    {

    public static void main(String[] args)

    {

    Test obj=new Test();

    int a=4,b=7;

    System.out.println("Before calling a="+a+" b="+b);

    obj.meth(a,b);

    System.out.println("After calling a="+a+" b="+b);}

    }

    O/P: Before calling a=4 b=7

    After calling a=4 b=7

    2. Call by Reference: In this method, a reference to an argument is passed to the parameter. Inside the parameter, this reference is used to access the actual argument specified in the call. Therefore, anychanges made to the parameter will effect the argument used to call it. This one is also referred as passingan object as parameter to a method.Example:

    class Test

    {

    int a,b;

    Test(int i,int j)

    {

    a=i; b=j;

    } O/P: Before calling a=4 b=5

    void meth(Test ox) After calling a=8 b=2

    {

    ox.a*=2; ox.b/=2;

    }

    }class cbr

    {

    public static void main(String[] args)

    {

    Test obj=new Test(4,5);

    System.out.println("Before calling a="+obj.a+" b="+obj.b);

    obj.meth(obj);

    System.out.println("After calling a="+obj.a+" b="+obj.b);

    }

    }

    Recursion: A recursive method is a method that calls itself either directly or indirectly through anothermethod. A method call itself is termed as Recursion.Example: fact(n) = 1 ; if n=0

    32

  • 8/3/2019 Java Notes-bsk (1)

    33/85

    n*fact(n-1) ; n 1// Write a program to print the factorial of a given number using recursionclass a

    {

    double fact(double x)

    {

    if(x==0)

    return 1;

    elsereturn x*fact(x-1);

    }

    }

    class recur

    {

    public static void main(String[] args)

    {

    a obj=new a();

    int p=Integer.parseInt(args[0]);

    double t=obj.fact(p);

    System.out.println("facatorial="+t);}

    }

    // Write a program to print the first n Fibonacci sequence numbers using recursion(Lab Program: 2)class a

    {

    int f(int x)

    {

    if(x==0||x==1)

    return x;

    else

    return (f(x-1)+f(x-2));

    }

    }

    class fibo

    {

    public static void main(String[] args)

    {

    a obj=new a();

    int p=Integer.parseInt(args[0]);

    for(int i=1;i

  • 8/3/2019 Java Notes-bsk (1)

    34/85

    The general formula for this type of problems using random method is a+(int)(Math.random( )*b).Where a is a shifting value that is equal to the fist number in the range of integers and b is the scalingfactor that is equal to the width of range of the integer.class random

    {

    public static void main(String[] args)

    {

    for(int i=1;i

  • 8/3/2019 Java Notes-bsk (1)

    35/85

    {

    outer y=new outer();

    y.test();

    }

    }

    StringsA string is a collection of characters. Java implements strings as object type of String. Java provides threetypes of string handling classes.

    1.String Class 2.StringBuffer Class 3.StringTokenizer ClassString and StringBuffer classes are defined in java.lang pacakage. StringTokenizer are defined in java.util

    package.

    1. String Class:A string is an object of class String. String literals or constants written as a sequence of characters indouble quotes. A string may be assigned in declaration to string reference as

    String color = blueIt initializes string reference color to refer the anonymous string object blue.

    Note: 1. Once we create a string object, we cannot change the contents of string instance.2. A variable declared as a string reference can be changed at any time.

    String Constructors: String class provides several types of constructors. They area) String( ): It creates an empty string with no characters in it.

    b) String(String): It takes one String as a parameter.c) String(StringBuffer): Allocates a new string that contains the sequence of characters currently

    contained in the string buffer argument.d) String(byte[] bytes): Construct a new String by converting the specified array of bytes using the

    platform's default character encoding.e) String(bytes byte[], int startindex, int numberofcharacters): Allocates new string positioned with

    the startindex by counting the number of charactes.f) String(char chars[]): Creates a string initialized by an array of characters.g) String(char chars[], int startindex, int numberofcharacters): Creates a string initialized by an array

    of characters with the startindex by counting the number of charactes.Methods:

    1. int length( ): It returns the number of characters in a given string.Example: String s1=new String(hello); System.out.println(s1.length());

    class len

    {

    public static void main(String[] args)

    {

    String s1=new String("hello"); System.out.println(s1.length());

    }

    }

    2. char charAt(int where): It returns the character at the specified location. where must be anonnegative specified location within the string. The first element of a string is considered to be at

    position zero.Example: class pos

    {

    public static void main(String[] args)

    {

    String s1=new String("hello java");

    char c=s1.charAt(7);

    System.out.println("character="+c);

    }}

    3. void getChars(int sourcestart, int sourceend, char target[], int targetstart): It extracts more than onecharacter at a time and copy the characters of the string into a character array.

    35

  • 8/3/2019 Java Notes-bsk (1)

    36/85

    The first argument is the starting index from which characters are copied in the string. The secondargument is the index that is one part of the last character to be copied from the string. The third argumentis the array into which the characters are copied. The last argument is the starting index where the copiedcharacters are placed in the character array.Example:class get

    {

    public static void main(String[] args)

    {String s1="java programming language";

    char c[]=new char[10];

    s1.getChars(3,8,c,0);

    for(int i=0;i

  • 8/3/2019 Java Notes-bsk (1)

    37/85

    {

    public static void main(String[] args)

    {

    String s1=new String("hello");

    String s2=new String("india");

    if((s1.compareTo(s2))>0)

    System.out.println("S1 is greater than s2");

    else if((s1.compareTo(s2))

  • 8/3/2019 Java Notes-bsk (1)

    38/85

    int indexOf(String str):

    int indexOf(char ch): It search for the first occurrence of a character. If the character is foundthe index of that characters in the string is returned. Otherwise, it returns -1.Example:

    class index

    {

    public static void main(String[] args)

    {

    String letter=new String("Java programming language");System.out.println(letter.indexOf('v')); //O/P: 2

    System.out.println(letter.indexOf("programming")); //O/P: 5

    System.out.println(letter.indexOf('A')); //O/P: -1

    }

    }

    9. int indexOf(int ch, int startIndex):

    int indexOf(String ch, int startIndex):

    int indexOf(char ch, int startIndex): It searches the occurrence of character from the startIndexargument.Example:

    class indexof{

    public static void main(String[] args)

    {

    String letter=new String("Java programming language");

    System.out.println(letter.indexOf('m',2)); //O/P: 11

    }

    }

    10. int lastIndexOf(int ch):

    int lastIndexOf(char ch):

    int lastIndexOf(String ch): It searches the last occurrence of the character. The search is performed

    from the end of the string towards the beginning of the string. If the character is found the index of thatcharacter in the string is return. Otherwise, it returns -1.Example:class lindexof

    {

    public static void main(String[] args)

    {

    String letter=new String("Java programming language");

    System.out.println(letter.lastIndexOf('n')); //O/P: 19

    System.out.println(letter.lastIndexOf("language")); //O/P: 17

    }}

    11. int lastIndexOf(int ch, int startIndex):

    int lastIndexOf(String ch, int startIndex):

    int lastIndexOf(char ch, int startIndex): It searches the last occurrence of the character startingwith the startIndex to search the string from ending to the beginning.Example:class lindexof

    { public static void main(String[] args)

    {

    String letter=new String("Java programming language");

    System.out.println(letter.lastIndexOf('n',11)); //O/P: -1}}

    12. String substring(int startIndex): It returns a copy of the sub string that begins that startIndex andreturn to the end of the invoking string.

    38

  • 8/3/2019 Java Notes-bsk (1)

    39/85

    Example:class sub

    {

    public static void main(String[] args)

    {

    String s=new String("Java programming language");

    System.out.println(s.substring(8));

    }

    }O/P: gramming language

    13. String substring(int startIndex, int endIndex): It returns all the characters from the beginning indexupto but not including the ending index.Example:class s13

    {

    public static void main(String[] args)

    {

    String s=new String("program");

    System.out.println(s.substring(2,5)); //O/P: ogr

    }}

    14. boolean startsWith(String str):

    boolean endsWith(String str): The startsWith( ) method determines whether a given string beginswith a specified string or not. Conversely, endsWith( ) method determines whether string ends with aspecified string or not.Example:class s14

    {

    public static void main(String[] args)

    {

    String s=new String("Java is a program");

    if(s.startsWith("is"))

    System.out.println("Match");

    else

    System.out.println("Not Match");

    }

    }

    //O/P: Not Match

    15. String concat(String str): It concatenates two string objects.Example:

    class s15{

    public static void main(String[] args)

    {

    String s=new String("Java ");

    String s1=s.concat("program");

    System.out.println(s1);

    }

    }

    O/P: Java program

    16. String replace(char original, char replacement): It replace all characters of one character in the

    invoking string with another character.

    Example:class s16

    39

  • 8/3/2019 Java Notes-bsk (1)

    40/85

    {

    public static void main(String[] args)

    {

    String s="Hello";

    System.out.println(s.replace('l','w')); //O/P: Hewwo

    }

    }

    17. String toLowerCase(): It converts all uppercase characters into lowercase characters of a string.

    Example:class s17

    {

    public static void main(String[] args)

    {

    String s="HELLO";

    System.out.println(s.toLowerCase()); //O/P: hello

    }

    }

    18. String toUpperCase():It converts all lowercase characters into uppercase characters of a string.Example:

    class s17{

    public static void main(String[] args)

    {

    String s="hello";

    System.out.println(s.toUpperCase()); //O/P: HELLO }

    }

    19. String trim(): It returns a copy of the invoking string from which any leading and lining white spacehas been removed.Example:class s18

    {

    public static void main(String[] args)

    {

    String s=" hello";

    System.out.println(s.trim());

    }

    }

    20. char[] toCharArray(): It returns a character array containing a copy of the characters in a string.Example:class s20

    { public static void main(String[] args)

    {

    String s="hello";

    char ch[]=s.toCharArray();

    for(int i=0;i

  • 8/3/2019 Java Notes-bsk (1)

    41/85

    class s21

    {

    public static void main(String[] args)

    {

    Integer i=new Integer(10);

    System.out.println(i.toString()); //O/P: 10

    }

    }

    LabProgram 5: Write a program to sort the list of names in ascending order.class lab5

    {

    public static void main(String[] args)

    {

    String ch[]={"india","hai","andhra"};

    String temp;

    for(int i=0;i

  • 8/3/2019 Java Notes-bsk (1)

    42/85

    Example:class sb1

    {

    public static void main(String[] args)

    {

    StringBuffer s=new StringBuffer("hello");

    System.out.println(s.length()); //O/P: 5

    }

    }2. int capacity(): It returns the number of characters that can be stored in a StringBuffer without allocatingmore memory.Example:class sb2

    {

    public static void main(String[] args)

    {

    StringBuffer s=new StringBuffer("hello");

    System.out.println(s.capacity()); //O/P: 21

    }

    }3. void ensureCapacity(): It is provided to allow the programmer to guarantee that a StirngBuffer has aminimum capacity where capacity specifies the size of the buffer.Example:

    class sb3

    {

    public static void main(String[] args)

    {

    StringBuffer s=new StringBuffer("hello");

    s.ensureCapacity(75);

    System.out.println(s.capacity()); //O/P: 75

    }

    }

    4. void setLength(int len): It increase or decrease the length of StringBuffer.Example:class sb4

    {

    public static void main(String[] args)

    {

    StringBuffer s=new StringBuffer("abcdefghijkl");

    s.setLength(5);

    System.out.println(s); //O/P: abcde}

    }

    5. char charAt(int where): It returns a character at the specified where position.Example:class sb5

    {

    public static void main(String[] args)

    {

    StringBuffer s=new StringBuffer("abcdefghijkl");

    System.out.println(s.charAt(7)); //O/P: h

    }}

    6. void setCharAt(int where, char ch): It takes an integer and a character argument and sets the characterat the specified position of the character argument.

    42

  • 8/3/2019 Java Notes-bsk (1)

    43/85

    Example:class sb6

    {

    public static void main(String[] args)

    {

    StringBuffer s=new StringBuffer("abcdef"); //O/P: Hbcdef

    s.setCharAt(0,'H');

    System.out.println(s);

    }}

    7. void getChars(int Sourcestart, int Sourceend, char Target[], int Targetstart): It copies the substring of a StringBuffer into character array. Sourcestart specifies the starting index from which charactersshould be copied in StringBuffer. Sourceend specifies the index one past the last character to be copiedfrom the StringBuffer. Target specifies the character array into which the characters are to be copied.Targetstart specifies the starting location of the character array from where the first character should be

    placed.Example:

    class sb7

    {

    public static void main(String[] args){

    StringBuffer s=new StringBuffer("abc def");

    char ch[]=new char[s.length()];

    s.getChars(3,s.length(),ch,0);

    for(int i=0;i

  • 8/3/2019 Java Notes-bsk (1)

    44/85

    1. int countTokens(): Using the current set of delimiters the method determines the number of tokens leftto be tokenized and return the result.2. boolean hasMoreTokens(): It returns true if one or more tokens remain in the string and returns false ifthere are none.3. String nextToken(): It returns the next token as string.Example:

    import java.util.*;

    class st

    {public static void main(String[] args)

    {

    String s=new String("abc def gh");

    StringTokenizer t=new StringTokenizer(s);

    System.out.println(t.countTokens());

    while(t.hasMoreTokens())

    System.out.println(t.nextToken());

    }}

    O/P: 3

    abc

    defgh

    LabProgram 7: Write a program that reads a line of integers, then displays each integers and the sum ofall the integersimport javax.swing.JOptionPane;

    import java.util.*;

    class lab7

    {

    public static void main(String[] args)

    {

    //String s=new String("4$8$9$67");

    //StringTokenizer t=new StringTokenizer(s,"$");

    String s;

    s=JOptionPane.showInputDialog("Enter the string");

    StringTokenizer t=new StringTokenizer(s,"$");

    int a,sum=0;

    System.out.println(t.countTokens());

    while(t.hasMoreTokens())

    {

    a=Integer.parseInt(t.nextToken());

    System.out.println(a);

    sum=sum+a;}

    System.out.println("Total="+sum);

    }}

    LabProgram 4: Write a program to check whether a given string is palindrome or not.

    import javax.swing.JOptionPane;

    class lab4

    {

    public static void main(String[] args)

    {

    String s;s=JOptionPane.showInputDialog("Enter a String");

    char ch[]=s.toCharArray();

    int i,j,count=0;

    44

  • 8/3/2019 Java Notes-bsk (1)

    45/85

    for(i=0,j=ch.length-1;i

  • 8/3/2019 Java Notes-bsk (1)

    46/85

    Unit IIIInheritance:The mechanism of deriving a new class from an old one is called inheritance. A class that isinherited (old class) is called a super class or base class or parent class. The class that does the inheriting(new class) is called a subclass or derived class or child class. Inheritance allows subclasses to inherit allthe variables and methods of their parent classes.

    Inheritance is classified into different forms.a) Single Inheritance: Derivation a subclass from only one super class is called Single Inheritance.

    Super class (or) Base class (or) Parent class

    Subclass (or) Derived class (or) Child classb) Hierarchical Inheritance: Derivation of several classes from a single super class is called HierarchicalInheritance.

    c) Multilevel Inheritance: Derivation of a class from another derived class s called Multilevel Inheritance.

    d) Multiple Inheritance: Derivation of one class from two or more super classes is called MultipleInheritance. But Java does not support Multiple Inheritance directly. It can be implemented by usingInterface concept.

    e) Hybrid Inheritance: Derivation of a class involving more than one form of Inheritance is called HybridInheritance.

    Defining a Subclass: A subclass is defined asSyntax: class subclass-name extends superclass-name

    {variable declaration;method declaration;

    }The keyword extends signifies that the properties of the super class name are extended to the

    subclass name. The subclass will now contain its own variables and methods as well as those of the superclass. But it is not vice-versa.Example 1: Program for Single Inheritance

    46

    A

    B

    A

    DCB

    A

    C

    B

    A

    C

    B

    A

    D

    CB

  • 8/3/2019 Java Notes-bsk (1)

    47/85

    class A

    {

    int len,bre;

    void getdata(int x,int y)

    {

    len=x; bre=y;

    }

    void printdata()

    {System.out.println("length="+len);

    System.out.println("Breadth="+bre);

    }

    }

    class B extends A

    {

    int wid;

    void putdata(int x,int y,int z)

    {

    len=x; bre=y;wid=z;

    }void printdata1()

    {

    printdata();

    System.out.println("Width="+wid);

    }

    void calarea()

    {

    int area=len*bre*wid;

    System.out.println("Area="+area);

    }

    }

    class si

    {

    public static void main(String[] args)

    {

    B obj=new B();

    obj.putdata(10,20,30);

    obj.printdata1();

    obj.calarea();

    }

    }Example 2: Program for Hierarchical Inheritanceclass A{

    int len,bre;

    void getdata(int x,int y)

    {

    len=x; bre=y;

    }

    void printdata()

    {

    System.out.println("length="+len);System.out.println("Breadth="+bre);}

    }

    class B extends A

    47

  • 8/3/2019 Java Notes-bsk (1)

    48/85

    {

    int wid;

    void getdata1(int x,int y)

    {

    getdata(x,y);

    }

    void calarea()

    {

    printdata();int area=len*bre;

    System.out.println("Area="+area);

    }

    }

    class C extends A

    {

    int wid;

    void putdata(int x,int y,int z)

    {

    len=x; bre=y;wid=z;

    }void printdata1()

    {

    printdata();

    System.out.println("Width="+wid);

    }

    void calarea1()

    {

    int area=len*bre*wid;

    System.out.println("Area="+area);

    }

    }

    class hi

    {

    public static void main(String[] args)

    {

    B obj=new B();

    obj.getdata1(10,20);

    obj.calarea();

    C obj1=new C();

    obj1.putdata(1,2,3);

    obj1.printdata1();obj1.calarea1();

    }

    }

    //Example Program for Hierarchical Inheritance

    import java.text.*;

    class Employee

    {

    int Empno;

    double Basic,DA,HRA;

    String Empname;

    void readdata(int x,String y){

    Empno=x;Empname=y;}

    void readsalary(double x,double y,double z)

    48

  • 8/3/2019 Java Notes-bsk (1)

    49/85

    {

    Basic=x;

    DA=y;

    HRA=z;

    }

    void printdata()

    {

    System.out.println("Employee Number:"+Empno);

    System.out.println("Employee Name :"+Empname);}

    void printsalary()

    {

    DecimalFormat df=new DecimalFormat("0.00");

    System.out.println("Employee Basic :"+df.format(Basic));

    System.out.println("Employee DA :"+df.format(DA));

    System.out.println("Employee HRA :"+df.format(HRA));

    }

    }

    class TSalary extends Employee

    {void showdata()

    {

    readdata(111,"Vishnu");

    printdata();

    readsalary(2589.00,567,1090);

    printsalary();

    }

    void calsalary()

    {

    DecimalFormat df=new DecimalFormat("0.00");

    double netsal;

    netsal=Basic+DA+HRA;

    System.out.println("Employee Netsalary="+df.format(netsal));

    }

    }

    class PSalary extends Employee

    {

    double Itax;

    void readtax(double x)

    {Itax=x;

    }

    void showdata()

    {

    readdata(1000,"Kamal");

    printdata();

    readsalary(12589.00,1567,2090);

    printsalary();

    }

    void calsalary()

    {DecimalFormat df=new DecimalFormat("0.00");

    double Gsal,netsal;

    Gsal=Basic+DA+HRA;

    49

  • 8/3/2019 Java Notes-bsk (1)

    50/85

    netsal=Gsal-Itax;

    System.out.println("Income Tax Amount="+df.format(Itax));

    System.out.println("Employee Netsalary="+df.format(netsal));

    }

    }

    class Harch

    {

    public static void main(String[] args)

    {TSalary obj=new TSalary();

    obj.showdata();

    obj.calsalary();

    PSalary obj1=new PSalary();

    obj1.readtax(800);

    obj1.showdata();

    obj1.calsalary();

    }

    }

    Example 3: Program for Multilevel Inheritance

    import javax.swing.JOptionPane;class student

    {

    int rno;

    void readdata1()

    {

    rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));

    }

    void printdata1()

    {

    System.out.println("Roll Number="+rno);

    }

    }

    class exam extends student

    {

    int m1,m2,m3;

    void readdata2()

    {

    readdata1();

    m1=Integer.parseInt(JOptionPane.showInputDialog("Enter sub1 marks"));

    m2=Integer.parseInt(JOptionPane.showInputDialog("Enter sub2 marks"));

    m3=Integer.parseInt(JOptionPane.showInputDialog("Enter sub3 marks"));}

    void printdata2()

    {

    printdata1();

    System.out.println("Sub 1 marks="+m1);

    System.out.println("Sub 2 marks="+m2);

    System.out.println("Sub 3 marks="+m3);

    }

    }

    class results extends exam

    {int avg;

    void printdata3()

    {

    50

  • 8/3/2019 Java Notes-bsk (1)

    51/85

    printdata2();

    avg=(m1+m2+m3)/3;

    if(avg=35 && avg=50 && avg=60 && avg=75)

    System.out.println("DISTINCTION");

    }

    }

    class mi

    {

    public static void main(String[] args)

    {

    results obj=new results();

    obj.readdata2();obj.printdata3();

    }

    }

    Member Access Rules:1. By means of sub class object it is possible to access all the instance variables and instance methods ofthe super class.2. By means of sub class object it cannot be possible to access the instance variable of super class, if it isdeclared as private. Since, the data is protected in that class.import javax.swing.JOptionPane;

    class student

    {

    private int rno;

    void readdata1()

    {

    rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));

    }

    }

    class exam extends student

    {

    void printdata1()

    {readdata1();

    System.out.println("Roll Number="+rno); // produces compilation error

    }

    }

    class mi2

    {

    public static void main(String[] args)

    {

    exam obj=new exam();

    obj.printdata1();

    }}

    51

  • 8/3/2019 Java Notes-bsk (1)

    52/85

    3. Referring to super class object with a subclass reference produces syntax error. In such case we needtype casting.Example:import javax.swing.JOptionPane;

    class student

    {

    int rno;

    void readdata1()

    {rno=Integer.parseInt(JOptionPane.showInputDialog("Enter roll number"));

    }

    }

    class exam extends student

    {

    void printdata1()

    {

    readdata1();

    System.out.println("Roll Number="+rno);

    }

    }class mi2

    {

    public static void main(String[] args)

    {

    student s1=new exam();

    exam e1=(exam)s1;

    e1.printdata1();

    }

    }

    super keyword: A subclass constructor is used to construct the instance variable of both the subclass andthe super class. The subclass constructor uses the keyword super to invoke the constructor method of thesuper class. The keyword super is used subject to the following conditions.

    super may be used only within the subclass constructor method

    The call to super class constructor must appear as the first statement with in the subclassconstructor

    If a parameterized constructor is used, then the signature is matched with the parameters passed tothe super method as super(parameter-list);

    Example 1:class student

    { public student()

    {System.out.println("super");

    }}

    class exam extends student

    {

    public exam()

    { System.out.println("sub");

    }}

    class s

    { O/P: super

    public static void main(String[] args) sub

    {exam obj=new exam();

    }

    52

  • 8/3/2019 Java Notes-bsk (1)

    53/85

    }a

    Example 2:class student

    {

    public student()

    {

    System.out.println("super");

    }

    }class exam extends student

    { public exam()

    {

    super( ); // explicit call of super( )

    System.out.println("sub");

    }

    }

    class s

    { public static void main(String[] args)

    {

    exam obj=new exam();}

    }

    O/P: super

    sub

    Example 3:class student

    { int len,bre;

    public student(int a,int b)

    {

    len=a; bre=b;

    }

    int area()

    {

    return len*bre;

    }

    }

    class exam extends student

    { int ht;

    public exam(int x,int y,int z)

    {

    super(x,y); ht=z;}

    int volume()

    {

    return len*bre*ht;

    }

    }

    class s

    { public static void main(String[] args)

    {

    exam obj=new exam(2,3,4);

    System.out.println("area="+obj.area());System.out.println("volume="+obj.volume());

    }

    }

    53

  • 8/3/2019 Java Notes-bsk (1)

    54/85

    Another important use of super is applicable to situations in which member names of a subclasshide members by the same name in the super class. It is similar to the this keyword except that it alwaysrefers to the super class of the subclass in which it is used. The general form is as

    super.member

    where member can be either a method or an instance variableExample:class A

    {int i=7;

    }

    class B extends A

    {

    int i=6;

    void show()

    {

    System.out.println("super i="+super.i);

    System.out.println("sub i="+i);

    }

    }class s1

    {

    public static void main(String[] args)

    {

    B obj=new B();

    obj.show();

    }

    }

    Method OverridingA method in a subclass has the same name, type of the variables and order of the variables as a

    method in its super class, then the method in the subclass is said to be override the method in the superclass. The process is called Method Overriding. In such process the method defined by the super classwill be hidden.

    When the method is called, the method defined in the super class has invoked and executed insteadof the method in the super class. The super reference followed by the dot (.) operator may be used toaccess the original super class version of that method from the subclass.

    Note: 1. Method Overriding occurs only when the name and type signature of the two methods areidentical.

    2. If method name is identical and the type signature is different, then the process is said to beMethod Overloading.

    Example 1:class A{

    int i,j;

    public A(int a,int b)

    {

    i=a;

    j=b;

    }

    void show()

    {

    System.out.println("i="+i+"\n"+"j="+j);}

    }

    54

  • 8/3/2019 Java Notes-bsk (1)

    55/85

    class B extends A

    {

    int k;

    B(int a,int b,int c)

    {

    super(a,b);

    k=c;

    }void show()

    {

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

    }

    }

    class override

    {

    public static void main(String[] args)

    {

    B obj=new B(1,2,3);

    obj.show();}

    }

    O/P: k=3

    Example 2:class A

    {

    int i,j;

    public A(int a,int b)

    {

    i=a; j=b;

    }

    void show()

    {

    System.out.println("i="+i+"\n"+"j="+j);

    }

    }

    class B extends A

    {

    int k;

    B(int a,int b,int c)

    {super(a,b);

    k=c;

    }

    void show()

    {

    super.show();

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

    } O/P: i=1

    } j=2

    class override k=3

    {public static void main(String[] args)

    {

    B obj=new B(1,2,3);

    55

  • 8/3/2019 Java Notes-bsk (1)

    56/85

    obj.show(); }}

    Resolve the method call at compile time is known as compile time or early binding or staticbinding. Resolve the method at run time is known as run time or late binding or dynamic binding.

    Method Overriding forms on the basis of Java concept Dynamic Method Dispatch. It is themechanism by which a call to an overridden function is resolved at run time, rather than compile time.And this method is very useful to show for Java implements run-time polymorphism.

    Super class reference variable can refer to a subclass object is the principle to resolve calls tooverridden methods at run time. If a super class contains a method that is overridden by a subclass, then

    when different types of objects are referred to through a super class reference variable, different version ofthe methods are executed and the determination is made at run time.Lab Program 21: Example program for Java supports Run time Polymorphism.class figure

    {

    double dim1,dim2;

    figure(double x,double y)

    {

    dim1=x;

    dim2=y;

    }

    double area(){

    System.out.println("Area undefined");

    return 0;

    }

    }

    class rectangle extends figure

    {

    rectangle(double a,double b)

    {

    super(a,b);

    }

    double area()

    {

    System.out.println("Rectangle Area");

    return dim1*dim2;

    }

    }

    class triangle extends figure

    {

    triangle(double x,double y)

    {super(x,y);

    }

    double area()

    {

    Sy