Computer Science – Introduction to Java ISC Notes

Embed Size (px)

Citation preview

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    1/10

    COMPUTER SCIENCE WITH JAVA

    Java- It is an object oriented language developed by Sun Microsystems in

    1991.

    Features of Java-

    It is portable, i.e., it can run on any operating system and platform.

    In java big applications require less code.

    It is an open product, i.e., freely available to all,

    It offers built in graphics.

    Types of Java Programs-There are two types of java programs,Internet

    applets and Stand alone applications. Internet Applets are small programs that are embedded in web pagesand are run on the viewers machine in a secured manner by Java capable

    browsers. Stand alone application is generally a software application that doesnot require low level operating system or hardware access.

    Java Byte Code- Java is a language which is both compiled and interpreted.Compiler converts source program intoJava Byte Code which looks like

    machine language.

    Java Virtual Machine- Java interpreter is known asJava Virtual Machine(JVM). It translates java byte code into machine language.

    BlueJ-It is aJava Development Environment. It was designed by BlueJteam atMonash University, Melbourne. It comprises of an editor, adebugger and a viewer.

    Object- An object is an identifiable entity with some characteristics andbehaviour. For example, a car, a mobile, etc. Object is also known as aninstance.

    Class- Class is a blueprint or data type according to which objects of thattype are created. For example, mobile is a class andNokia6630 is anexample of that class.

    Abstraction- Abstraction refers to the act of representing essential featureswithout including the background details.

    -1-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    2/10

    Encapsulation- The wr4apping up of data and functions (that operate onthe data) into a single unit (called class) is called encapsulation.

    Inheritance- A class calledsub-class inherits certain characteristics andbehaviour from another class calledsuper-class. This is termed as

    inheritance.

    Polymorphism- When different objects interpret a single messagedifferently and respond it differently, it is known as polymorphism.Unicode- Unicode is a two byte character code set which represents almostall characters used by different languages of the world (65,536 characters).Java uses Unicode character set.

    Token- The smallest individual unit in a program is called token. Java has

    following token: keywords, identifiers, literals, punctuators and operators.

    Keywords- These are the reserved words and have special meaning.

    Identifiers- Identifiers are the names given to variables, objects, classes,functions, arrays, etc.

    Rules for naming identifiers:

    Alphabets, digits, underscore and $ can be used.

    Keywords cannot be used.

    Must not begin with a digit.

    Can be of any length.Java is case sensitive.

    Literals (constants)- These are values that are fixed. Java has followingconstants:

    integer constants- e.g., 12,-38976, etc.

    floating constants- e.g., 3.5F, 11.465D, 12E7, -0.132E-3, etc.

    boolean constants- e.g., true, false.

    character constants- e.g., w, &, 6, etc. String constants- e.g., India, computer, o, etc.

    Punctuators- These are special characters which act as separators in java.e.g., ( ), { },[ ], ;,.

    Operators- These are symbols which represent various operations that arebeing carried on data.

    Unary operator- These operate on a single operand. e.g. +, -, ++, --. Binary operator- These operate on two operands. e.g., *, %,/, etc.

    There are following operators: Arithmetic operators: +, -, *,/, %.

    -2-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    3/10

    Increment operator: ++

    Decrement operator: --

    Relational operators: >, >=,

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    4/10

    Reference datatypes- A reference in java is a data element whose valueis an address. Arrays and classes are reference datatypes.

    Dynamic Initialization- When a variable is initialization by the return valueof a method call it is termed as dynamic initialization.

    Block- A block is a set of statements enclosed within curly brackets.

    Compound Statement- It is a set of one or more statements.

    Scope of a variable- The scope of a variable is defined as the area ofprogram where the variable is visible (accessible). Variables declared withina method are local to that method only. Variables declared within a block areaccessible only within that block.

    Lifetime of a variable- Lifetime of a variable is the duration for which avariable exists. Variables local to a method exist as long as the methodexecutes.

    rvalue- Actual read value is the value stored in a variable. E.g. int a = 7;here 7 is the rvalue.

    lvalue-Location value is the memory address of the variable.

    Type conversion /casting- Process of converting one datatype to another iscalled type conversion. Implicit typeconversion- Lower datatypes are automatically convertedto higher datatype in expression whenever different datatypes areintermixed. This is also called type promotion.

    Explicit type conversion- Explicit (forced) conversion of one datatypeto another is called explicit type casting. Syntax: (type)expression

    if else statement- It is a conditional branch statement. If the conditionevaluates to true, ifpart is executed otherwise else part is executed.

    switch statement- It is a multi-way branch selection statement, depending onthe value of the expression, particular case statement is executed.

    default statement- If none of the constant matches the value of theexpression in aswitch statement, then the defaultstatement is executed. Thedefaultstatement is optional.

    -4-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    5/10

    Differences between if-else and switch-

    if-else switch

    Can evaluate any type of booleanexpression.

    Floating point variables can be

    used. Less efficient but more versatile.

    Can only test for equality.

    Floating point variables cannot

    be used. More efficient but less versatile.

    Ternary operator- it requires three operands. General form is:expression1? expression2? expression3

    expression1 is a condition. If it evaluates to true, expression2 is the resultelse expression3 is the result.

    for loop- It is a looping statement used to repeat statements a fixed number

    of times. General form is:for(initialization; condition; updation){

    Statement;}

    while loop- It is a looping statement used to repeat statements as long as thecondition remains true. It is used when it is not known how many timesstatements are to be repeat. It is also known as entry controlled loop.

    do while loop- It is a looping statement used to repeat statement as long asthe condition remains true. It is used when it is not known how many timesstatements are to be repeated. It is also known as exit controlled loop.

    Differences between while and do while loops-

    while do while

    Condition is checked beforeentering the loop.

    while loop may not execute evenonce.

    Condition is checked at the bottomof the loop.

    do while loop always executes atleast once.

    break statement- It is a jump statement which causes the termination ofswitch statement, for loop, while loop and do while loop.

    continue statement- It causes the control to skip remaining statement of theloop and to proceed with the next iteration of the loop.

    Break and continue are generally used with if.

    Empty loop- An empty loop does not contain any statement in its loop body.E.g.,for (int x =1; x

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    6/10

    Infinite loop- An infinite loop executes endlessly. It can be created byomitting condition.E.g.,for (int x =1; ; x ++)

    {

    System.out.println(This is an endless loop);}

    Method/Function- A method is a subprogram which contains instructions toperform a specific task. Each method has a unique name and may or may notreturn a value.

    Formal Parameters- Variables defined within the parentheses that receivethe values when the function is called are called formal parameters.

    Arguments- They are also called actual parameters. They are the valuespassed to a method when it is called.

    Pure Methods- They are also calledAccessor methods. These methods donot change the state of the object. They just provide the information aboutthe state of the object.

    Impure Methods- They are also called mutator methods. They change the

    state of the object.

    Function Prototype- It is the first line of the function definition. It givesinformation about the type of value returned by the function and type of

    parameter that function receives.

    Function signature- Signatures refers to the number and type of argument.

    Return statement- It is used in two ways:a) It causes an immediate exit from the function when it is encountered.

    b) It is used to return a value to the calling code.

    Static methods- These are also called class methods. These are not calledthrough objects rather they are called through class itself.

    Call by value (pass by value)- In this method of function call, actualparameters are copied in the formal parameters hence actual and formalparameters are different. The changes made to the formal parameters are notreflected in the actual parameters.

    In java all primitive types are passed by value.

    -6-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    7/10

    Call by reference- In this method of function call, the formal parametersbecome the references to the actual and formal refer to the same values. Thechanges are reflected in the original values.

    In java objects and arrays are passed by reference.

    Function overloading- Having more than one function with the same namewhich can be differentiated by the number and types of arguments is calledfunction overloading. Function overloading implements polymorphism.

    Constructor- A member function with the class name is called constructor. Itis used to initialize the objects of that class when they are created.Constructors have no return type, not even void.

    Default constructor- A constructor which receives no parameters is calleddefault constructor. It is also called non parameterizedconstructor.

    If in a class no constructor is defined, Java supplies a default constructorwhich initializes instance variables with dummy values.

    Parameterized constructor- A constructor which receives parameters iscalled parameterized constructor.

    Constructor overloading-Having more than oneconstructor in a class istermed a constructor overloading.It is a feature of polymorphism.

    Package- A package is a group of logically related classes. E.g.,java.io,java.lang,java.applet,java.util,java.net, etc.

    Instance variables- Variables defined within the class which representsattributes are called instance variables. They are also called data membersand are created for every object of the class.

    Static variables- These are also called class variables. These are common forall the objects of the class.

    Access specifiers- These are access levels which control access to membersof a class. There are four types of access specifiers:

    private-privatemembers of a class are accessible only within theclass.

    public- public members of a class are accessible from any class of anypackage.

    protected- protected members of a class are accessible from the classof the same package and all the subclasses.

    package/default/friendly- when no access specifier is used, access is

    friendly. All the classes of the same package can access such members.

    -7-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    8/10

    new Operator- New is used to create objects and arrays. It is used to allocatememory for objects and arrays.

    this Operator - When an object calls a member function, the functionautomatically passes an in built argument which is a reference to the object

    that called the function. The reference is called this.

    Stream- Stream refers to the flow of data.

    Input stream- A source of input data is called an input stream.

    Output stream- Output data is called an output stream.

    Compile time errors- These errors are detected at the time of compilation.

    These arise because of improper syntax.

    Run time errors- Errors that occur at the time of execution are called runtime errors.

    Exception- Run time errors are called exception. These are treated as objectsin java.

    Wrapper classes- These are part of java.lang package. A wrapper class

    wraps a value of primitive type in an object. E.g., Character, Boolean, Byte,Short, Integer, Long, Float, Double.

    Exception handling-Exception handlingrefers to the way of handlingexceptions by writing handlers (programs).

    try{ }- Lines of codes that are part of normal processing are placed within tryblock.

    catch{ }- Code to deal with an exceptions that might arise during theexecution of the program is written within catch block.

    finally block- Code that must be executed whether an exception occurs ornot is written within finally block.

    throws-Throwskeyword is used to inform java compiler about theexception that might arise. After throws exception class name is givenwhose exception might arise.

    Array- An array is a finite set of data itemsstored in continuous memorylocations referred to by a single name.

    -8-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    9/10

    Subscript- Subscript refers to the position of the element within the array. Itvaries from 0 to number of elements-1.

    Single dimensional array- Here elements are referred by one subscript only.

    int [ ] a=new int [0];// creates an array with ten memory locations.

    Double dimensional array- Elements are referred by two subscripts. Firstsubscript refers to row and second to columns.int [ ] [ ] a= new int [5] [3];// creates an array with 5rows and 3colums.

    length- It is a property of array used to find the number of elements in thearray.

    arraycopy( )- This method is used to copy data from one array to another.System.arraycopy(source array, source index, destination array, destination

    index, no of elements to be copied).

    Linear searching- This is a method of searching an element in an array.Element to be searched is compared with every array element till it is found.It is time consuming if the array is large.

    Binary searching- This takes place in array arranged in ascending or

    descending order. The middle subscript of the element is calculated. Thevalue to be searched is compared with middle positioned element. If value isless than middle element (assuming array is sorted in ascending order),search takes place in the first half of the array otherwise takes place in thesecond half of the array. The above process is repeated till the element isfound if present. This process takes less time as the numbers of comparisonsare reduced.

    Sorting- The process of arranging element in ascending or descending orderis calledsorting.

    Selection sorting- If the array is to be arranged in ascending order, thesmallest element needs to be searched and exchanged with the first positionelement in the array. Again the smallest element from the remainingelements is selected and exchanged with second array element. This processcontinues till all elements are arranged. If the array needs to be arranged inthe descending order, select the largest element.

    Bubble sorting- The adjacent elements of the array are compared. If array

    has to be arranged in ascending order and ifa[0] is greater than a[1] they are

    -9-

  • 7/31/2019 Computer Science Introduction to Java ISC Notes

    10/10

    swapped(process of exchanging values is called swapping). This continues tillelements are sorted.

    -10-