Java Programming Basics


Published on

In this file you'll find quick revision of core java. All the basics...

Published in: Technology, News & Politics
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java Programming Basics

  1. 1. TRAINING REPORT CORE JAVA CHAPTER 1 INTRODUCTION TO JAVA 1.1 The beginning of Java Java is an object-oriented programming language developed by Sun Microsystems in 1991 and released in 1995 as a core component of Sun’s Java platform. The language derives much of its syntax from C and C++, but has a simpler object model and fewer low level facilities. The Java language was designed to be small, simple, and portable across platforms and operating systems. The Java language was developed as part of a research project to develop software for consumer electronics devices—television sets, VCRs, toasters, and the other sorts of machines we can buy at any department store. Java’s goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. 1.2 The family history of Java Before going on to study Java, let’s take a brief look, through quotes, at the language on which Java was based, travelling back over 30years to do so. 1.2.1 Where it starts: C The earliest precursor of Java is C: a language developed by Ken Thompson at Bell Labs in the early 1970s. C was used as a system programming language. C began achieving its widespread popularity when Bell’s UNIX operating system was rewritten in C. Unix was the first operating system written in high level language; it was distributed to universities for free, where it become popular. Linux is currently a popular variant of UNIX. “C is a general purpose programming language which feature economy of expression, modern control flow and data structure, and a rich set of operators. C is not a “very high level” language, nor a “big” one, and is not specialized to any particular area of application. 1.2.2 From C to C++ “A programming language serves two related purpose: it provide a vehicle for the programmers to specify action to be executed, and it provides a set of concepts for the programmers to use when thinking about what can be done. The first aspect ideally requires a language that is “close to the machine,” so that all important aspect of the machine are DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 1
  2. 2. TRAINING REPORT CORE JAVA handled simply and efficiently in a way that is reasonably obvious to the programmer. The C language was primarily designed with this in mind. The second aspect ideally requires a language that is “close to the problem to be solved,” so that the concept of a solution can be expressed directly and concisely. The facilities added to C to create C++ were primarily designed with this in mind.” 1.3 Java as a successor to C++ “The Java programming language is a class-based, general purpose, concurrent, objectoriented language. It is designed to be simple enough that many programmers can achieve fluency in the language. The Java programming language is related to C and C++ but it is organized rather differently, with a number of aspects of C and C++ omitted and a few ideas from other languages included. It is intended to be production language, not a research language, and so, as C.A.R. Hoare suggested in his classic paper on language design, the design has avoided including new and untested features. The Java programming language is a relatively high level language, in that detail of the machine representation are not available through the language. It includes automatic storage management, typically using a garbage collector, to avoid the safety problems. High performance garbage collected implementation can have bounded pauses to support system programming and real time application. The language does not includes any unsafe construct, such as array accesses without checking, since such unsafe constructs would cause a program to behave in an unspecified way.” 1.4 What is the Java Technology?  A programming language: - We can use java as a programming language. By using this programming language we can develop different type of application for eg: Console Application (CUI), Window Application (GUI) and Web Applications.  A development environment: - It provides a development environment in which we can develop, check, debug and execute the applications.  An application environment: - It provides an environment in which application can run or execute.  A deployment environment: - It provides a deployment environment in which we can check application after deployment how application will react. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 2
  3. 3. TRAINING REPORT  CORE JAVA It is similar in syntax to C++. 1.5 Features of Java Features of Java are as follows: 1. Compiled and Interpreted 2. Platform Independent and portable 3. Object- oriented 4. Robust and secure 5. Distributed 6. Familiar, simple and small 7. Multithreaded and Interactive 8. High performance 9. Dynamic and Extensible 1. Compiled and Interpreted Basically a computer language is either compiled or interpreted. Java comes together both these approach thus making Java a two-stage system. Java compiler translates Java code to Byte-code instructions and Java Interpreter generate machine code that can be directly executed by machine that is running the Java program. 2. Platform Independent and portable Java supports the feature portability. Java programs can be easily moved from one computer system to another and anywhere. Changes and upgrades in operating systems, processors and system resources will not force any alteration in Java programs. This is reason why Java has become a trendy language for programming on Internet which interconnects different kind of systems worldwide. Java certifies portability in two ways. First way is, Java compiler generates the byte-code and that can be executed on any machine. Second way is, size of primitive data types are machine independent. 3. Object- oriented Java is truly object-oriented language. In Java, almost everything is an Object. All program code and data exist in objects and classes. Java comes with an extensive set of classes; organize in packages that can be used in program by Inheritance. The object model in Java is trouble-free and easy to enlarge. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 3
  4. 4. TRAINING REPORT CORE JAVA 4. Robust and secure Java is a most strong language which provides many securities to make certain reliable code. It is design as garbage –collected language, which helps the programmers virtually from all memory management problems. Java also includes the concept of exception handling, which detain serious errors and reduces all kind of threat of crashing the system. Security is an important feature of Java and this is the strong reason that programmer use this language for programming on Internet. The absence of pointers in Java ensures that programs cannot get right of entry to memory location without proper approval. 5. Distributed Java is called as Distributed language for construct applications on networks which can contribute both data and programs. Java applications can open and access remote objects on Internet easily. That means multiple programmers at multiple remote locations to work together on single task. 6. Simple and small Java is very small and simple language. Java does not use pointer and header files, go to statements, etc. It eliminates operator overloading and multiple inheritance. 7. Multithreaded and Interactive Multithreaded means managing multiple tasks simultaneously. Java maintains multithreaded programs. That means we need not wait for the application to complete one task before starting next task. This feature is helpful for graphic applications. 8. High performance Java performance is very extraordinary for an interpreted language, majorly due to the use of intermediate byte-code. Java architecture is also designed to reduce overheads during runtime. The incorporation of multithreading improves the execution speed of program. 9. Dynamic and Extensible Java is also dynamic language. Java is capable of dynamically linking in new class, libraries, methods and objects. Java can also establish the type of class through the query building it possible to either dynamically link or abort the program, depending on the reply. Java program is support functions written in other language such as C and C++, known as native methods. These are various features of Java programming. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 4
  5. 5. TRAINING REPORT CORE JAVA 1.5 Comparison in Java and C++ Java C++ Java is true Object-oriented language. C++ is basically C with Object-oriented Extension. 1 Java does not support operator 2 C++ supports operator overloading. overloading It supports labels with loops and 3 It supports goto statement statement blocks Java does not have template classes as in C++ has template classes 4 C++. Java does not support multiple 5 C++ supports multiple inheritance of inheritance of classes but it supports classes. interface 6 Runs in a protected virtual machine. Exposes low-level system facilities. 7 There are no header files in Java. We have to use header file in C++ Table: - 1.1 Comparison in Java and C++ 1.6 Java Virtual Machine As we know that all programming language compilers convert the source code to machine code. Same job done by Java Compiler to run a Java program, but the difference is that Java compiler convert the source code into Intermediate code is called as byte-code. This machine is called the Java Virtual machine and it exits only inside the computer memory. Following figure shows the process of compilation. Java Program Java compiler Source Code Virtual Machine Byte Code Fig: - 1.1 Compilation process DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 5
  6. 6. TRAINING REPORT CORE JAVA The Virtual machine code is not machine specific. The machine specific code is generated. By Java interpreter by acting as an intermediary between the virtual machine and real machines shown below. Byte Java Interpreter Machine code Code Virtual Machine Real Machine Fig: - 1.2 Java Interpreter Java Object Framework act as the intermediary between the user programs and the virtual machine which in turn act as the intermediary between the operating system and the Java Object Framework. Operating System Java Virtual Machine Java Object Framework Compiler and Interpreter User Application Programs User Fig: -1.3 Layers of Interaction for Java programs DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 6
  7. 7. TRAINING REPORT CORE JAVA CHAPTER 2 JAVA LANGUAGE FUNDAMENTAL 2.1 Data Type Data type specifies the size and type of values that can be stored in an identifier. The Java language is rich in its data types. Different data types allow we to select the type appropriate to the needs of the application. Data types in Java are classified into two types: 1. Primitive—which include Integer, Character, Boolean, and Floating Point. 2. Non-primitive—which include Classes, Interfaces, and Arrays. 2.1.1 Primitive Data Types 1. Integer Integer types can hold whole numbers such as 123 and −96. The size of the values that can be stored depends on the integer type that we choose. Type Size Range of values that can be stored Byte 1 byte −128 to 127 Short 2 byte −32768 to 32767 Int 4 bytes −2,147,483,648 to 2,147,483,647 Long 8 bytes 9,223,372,036,854,775,808 to 9,223,372,036,854,755,807 The range of values is calculated as - (2n−1) to (2n−1) −1; where n is the number of bits required. For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of values that can be stored in the byte data type is −(28−1) to (28−1)−1 = −27 to (27) -1 = −128 to 127 2. Floating Point Floating point data types are used to represent numbers with a fractional part. Single precision floating point numbers occupy 4 bytes and Double precision floating point numbers occupy 8 bytes. There are two subtypes: Type Size Range of values that can be stored Float 4 bytes 3.4e−038 to 3.4e+038 Double 8 bytes 1.7e−308 to 1.7e+038 DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 7
  8. 8. TRAINING REPORT CORE JAVA 3. Character It stores character constants in the memory. It assumes a size of 2 bytes, but basically it can hold only a single character because char stores Unicode character sets. It has a minimum value of ‘u0000′ (or 0) and a maximum value of ‘uffff’ (or 65,535, inclusive). 4. Boolean Boolean data types are used to store values with two states: true or false. 2.2 Java Tokens A token is the smallest element in a program that is meaningful to the compiler. These tokens define the structure of the language. The Java token set can be divided into five categories: Identifiers, Keywords, Literals, Operators, and Separators. 2.2.1 Identifiers Identifiers are names provided by we. These can be assigned to variables, methods, functions, classes etc. to uniquely identify them to the compiler. 2.2.2 Keywords Keywords are reserved words that have a specific meaning for the compiler. They cannot be used as identifiers. Java has a rich set of keywords. Some examples are: boolean, char, if, protected, new, this, try, catch, null, threadsafe etc. 2.2.3 Literals Literals are variables whose values remain constant throughout the program. They are also called Constants. Literals can be of four types. They are: a. String Literals: - String Literals are always enclosed in double quotes and are implemented using the java.lang.String class. Enclosing a character string within double quotes will automatically create a new String object. For example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. b. Character Literals: - These are enclosed in single quotes and contain only one character. c. Boolean Literals: - They can only have the values true or false. These values do not correspond to 1 or 0 as in C or C++. d. Numeric Literals: - Numeric Literals can contain integer or floating point values. 2.2.4 Operators DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 8
  9. 9. TRAINING REPORT CORE JAVA An operator is a symbol that operates on one or more operands to produce a result. Operator Meaning Operator + Addition & – Meaning AND Subtraction ¦ * Multiplication OR ^ XOR ÷ Division << Left shift % Modulus >> Right shift < Less than >>> Zero fill right shift > Greater than ~ Complement ≤ Less than or equal to = Assignment ≥ Greater than or equal to ++ Increment == Equal – – Decrement != Not equal += Add and assign Logical AND –= Subtract and assign Logical OR *= Multiply and assign Logical NOT ÷= Divide and assign AND and assign %= Modulus and assign && ¦¦ ! &= ¦= <<= OR and assign Left shift and assign >>= >>>= Right shift and assign Zero fill right shift and assign Table: 2.1 Operators 2.2.5 Separators Separators are symbols that indicate the division and arrangement of groups of code. The structure and function of code is generally defined by the separators. The separators used in Java are as follows: Parentheses ( ): - Used to define precedence in expressions, to enclose parameters in method definitions, and enclosing cast types. Braces { }: - Used to define a block of code and to hold the values of arrays. Brackets [ ]: - Used to declare array types. Semicolon; : - Used to separate statements. Comma,: - Used to separate identifiers in a variable declaration and in the for statement. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 9
  10. 10. TRAINING REPORT CORE JAVA Period. : - Used to separate package names from classes and subclasses and to separate a variable or a method from a reference variable. 2.3 Variables There are different types of variables in Java. They are as follows: 2.3.1 Instance Variables (Non-Static Fields) Objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class. For example, the current Speed of one bicycle is independent from the current Speed of another. 2.3.2 Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since, conceptually, the same number of gears will apply to all instances. The code static int num Gears = 6; would create such a static field. 2.3.3 Local Variables A method stores its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared—between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. 2.3.4 Parameters They are the variables that are passed to the methods of a class. 2.4 Variable Declaration Identifiers are the names of variables. They must be composed of only letters, numbers, the underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only begin with a letter, the underscore, or the dollar sign. A variable cannot begin with a number. All variable names are case sensitive. 2.4.1 Syntax DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 10
  11. 11. TRAINING REPORT CORE JAVA datatype1 variable1, datatype2 variable2, … datatypen variablen; For example: int a, char ch; 2.4.2 Initialization Variables can be assigned values in the following way: Variablename = value; For example; ch='a'; a=0; 2.5 Arrays An array is a group of variables that share the same data type, and are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. The array index ranges from 0 to n−1; therefore, in an array of size 10, the first element is stored at index 0 and the last or the 10th element at index 9. 2.6 A simple java program Syntax: class class_name { public static void main(String args[]) { //wer statement goes here } } Example: class Employee { public static void main(String args[]) { System.out.println(“Hello, This is simple java program”); } } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 11
  12. 12. TRAINING REPORT CORE JAVA CHAPTER 3 OOPS CONCEPTS 3.1 OOPS Concept Object-Oriented Programming system (OOPS) is a programming paradigm using "objects" to design applications. An object is a thing which has its own identity. An object contains both state and behavior. State of an object is the current data and behavior is implemented as methods. An object in an OO language can be easily compared to a real world object. Consider a car. A car has some properties like model, fuel type etc which are the state (or properties) of that object. Similarly it will also have functions. Object-Oriented Programming (OOP) has certain important features like Encapsulation, Polymorphism, Inheritance and Abstraction. These features are also referred to as OOPS concepts. Java is an object oriented language. Java, unlike some other languages, is considered as a pure object oriented language as everything in java should be enclosed, basically inside a class. There can be no global variables or functions. In addition to classes, we can have interfaces as well. But we will restrict our discussion here to classes only. 3.2 Features of OOPS 1. Class 2. Object 3. Data abstraction 4. Data encapsulation 5. Inheritance 6. Polymorphism 3.3 Class A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 12
  13. 13. TRAINING REPORT CORE JAVA states of a class’s corresponding object are stored in the object’s instance variables. Methods define the operations that can be performed in java programming. A class has the following general syntax: <class modifiers>class<class name> <extends clause> <implements clause> { // Dealing with Classes (Class body) <field declarations (Static and Non-Static)> <method declarations (Static and Non-Static)> <Inner class declarations> <nested interface declarations> <constructor declarations> <Static initializer blocks> } Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume(). public class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } } This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object.( objectReference.member ). We call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3). For example: DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 13
  14. 14. TRAINING REPORT CORE JAVA cubeObject.length=4; cubeObject.breadth=4; cubeObject.height=4; cubeObject.getvolume() 3.3.1 Class Variables – Static Fields We use class variables also known as Static fields when we want to share characteristics across all objects within a class. When we declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword. 3.3.2 Class Methods – Static Methods Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. We cannot call nonstatic methods from inside a static method. 3.3.3 Instance Variables Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence. 3.4 Object An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 14
  15. 15. TRAINING REPORT CORE JAVA references, which can be stored in variables. Creating variables of our class type is similar to creating variables of primitive data types, such as integer or float. Each time we create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If we want to create an object of the class and have the reference variable associated with this object, we must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance. When we create a new object, we use the new operator to instantiate the object. The new operator returns the location of the object which we assign o a reference type. Below is an example showing the creation of Cube objects by using the new operator. public class Cube { int length = 10; int breadth = 10; int height = 10; public int getVolume() { return (length * breadth * height); } public static void main(String[] args) { Cube cubeObj; // Creates a Cube Reference cubeObj = new Cube(); // Creates an Object of Cube System.out.println("Volume of Cube is : " + cubeObj.getVolume()); } } 3.5 Data abstraction Abstract means a concept or idea not associated with any specific instance and does not have a concrete existence. Abstraction in Object Oriented Programming refers to the ability to make a class abstract. Abstraction captures only those details about an object that are relevant to the current perspective. Abstraction tries to reduce and factor out details so that the programmer can focus on a few concepts at a time. Java provides interfaces and abstract classes for describing abstract types. An interface is a contract or specification without any DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 15
  16. 16. TRAINING REPORT CORE JAVA implementation. An interface can't have behavior or state. An abstract class is a class that cannot be instantiated. All other functionality of the class still exists. Abstract classes can have state and can be used to provide a skeletal implementation. Abstraction is simplifying complex reality by modelling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem. For example, Lassie the Dog may be treated as a Dog much of the time, a Collie when necessary to access Colliespecific attributes or behaviors, and as an Animal (perhaps the parent class of Dog) when counting Timmy's pets. Abstraction is also achieved through Composition. For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other. Basically Data abstraction refers to the act of representing important description without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, cost and functions operate on these attributes. They summarize all the important properties of the objects that are to be created. Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT). 3.5.1 Abstract class An abstract class is something which is incomplete and we cannot create instance of abstract class. If we want to use it we need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended. By the way Java has concept of abstract classes, abstract method but a variable cannot be abstract in Java. Popular example of abstract class in Java is ActionListener which has abstract method called actionPerformed(ActionEvent ae). This method is called when an ActionEvent is fired like when we click on JButton. Its common in java to attach ActionListener with JButton by implementing abstract method actionPerformed(ActionEvent ae) using Anonymous class, as shown in below Example : JButton ok = new JButton("OK"); ok.addActionListener(new ActionListener(){ DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 16
  17. 17. TRAINING REPORT CORE JAVA public void actionPerformed(ActionEvent ae){ //code to handle event } }); An abstract method in Java doesn't have body, it’s just a declaration. In order to use abstract method we need to override that method in SubClass. 3.6 Data encapsulation Encapsulation in Java is the process of wrapping up of data (properties) and behavior (methods) of an object into a single unit; and the unit here is a Class (or interface). Encapsulate in plain English means to enclose or be enclosed in or as if in a capsule. In Java, a class is the capsule (or unit). In Java, everything is enclosed within a class or interface, unlike languages such as C and C++, where we can have global variables outside classes. Encapsulation enables data hiding, hiding irrelevant information from the users of a class and exposing only the relevant details required by the user. We can expose our operations hiding the details of what is needed to perform that operation. We can protect the internal state of an object by hiding its attributes from the outside world (by making it private), and then exposing them through setter and getter methods. Now modifications to the object internals are only controlled through these methods. Consider the example of a linked list’s getsize method. We might be now using a variable named size that is updated on every insert / delete operation. Later we might decide to traverse the list and find size every time someone ask for size. But if some code was directly accessing the size variable, we would have to change all those code for this change. However if we were accessing the size variable through a getsize method, other code can still call that method and we can do our changes in that method. A setter is a method used to change the value of an attribute and a getter is a method used to get the value of an attribute. There is also a standard naming convention for getters and setters, but Java compiler won't complain even otherwise. Example: Consider a variable name and its getter and setter: private String name; public String getName() { DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 17
  18. 18. TRAINING REPORT CORE JAVA return name; } public void setName(String name) {; } 3.7 Inheritance Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or acquire the properties and methods of other classes. A class derived from another class is called a subclass, whereas the class from which a subclass is derived is called a superclass. A subclass can have only one superclass, whereas a superclass may have one or more subclasses. The keyword “extends” is used to derive a subclass from the superclass, as illustrated by the following syntax: class Name_of_subclass extends Name_of superclass {//new fields and methods that would define the subclass go here} If we want to derive a subclass Rectangle from a superclass Shapes, we can do it as follows: class Rectangle extends Shapes { …. }. Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y. For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy. Example: class Box { double width; double height; DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 18
  19. 19. TRAINING REPORT CORE JAVA double depth; Box() { } Box(double w, double h, double d) { width = w; height = h; depth = d; } void getVolume() { System.out.println("Volume is : " + width * height * depth); } } public class MatchBox extends Box { double weight; MatchBox() { } MatchBox(double w, double h, double d, double m) { super(w, h, d); weight = m; } public static void main(String args[]) { MatchBox mb1 = new MatchBox(10, 10, 10, 10); mb1.getVolume(); System.out.println("width of MatchBox 1 is " + mb1.width); System.out.println("height of MatchBox 1 is " + mb1.height); System.out.println("depth of MatchBox 1 is " + mb1.depth); System.out.println("weight of MatchBox 1 is " + mb1.weight); } } 3.7.1 ‘this’ and ‘super’ keywords The two keywords, this and super to help we explicitly name the field or method that we DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 19
  20. 20. TRAINING REPORT CORE JAVA want. Using this and super we have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class. The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object. class Counter { int i = 0; Counter increment() { i++; return this; } void print() { System.out.println("i = " + i); } } public class CounterDemo extends Counter { public static void main(String[] args) { Counter x = new Counter(); x.increment().increment().increment().print(); } } } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 20
  21. 21. TRAINING REPORT CORE JAVA 3.8 Polymorphism The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the capacity to take on different forms’. When applied to object oriented programming languages like Java, it describes a language’s ability to process objects of various types and classes through a single, uniform interface. Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism. An important example of polymorphism is how a parent class refers to a child class object. In fact, any object that satisfies more than one IS-A relationship is polymorphic in nature. For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its super class Animal. 3.8.1 Static Polymorphism In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters. At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile time polymorphism or static binding. The concept will be clear from the following example: class DemoOverload { public int add(int x, int y) { //method 1 return x+y; } public int add(int x, int y, int z) { //method 2 return x+y+z; } public int add(double x, int y) { //method 3 return (int)x+y; DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 21
  22. 22. TRAINING REPORT CORE JAVA } public int add(int x, double y) { //method 4 return x+(int)y; } } class Test { public static void main(String[] args) { DemoOverload demo=new DemoOverload(); System.out.println(demo.add(2,3)); //method 1 called System.out.println(demo.add(2,3,4)); //method 2 called System.out.println(demo.add(2,3.4)); //method 4 called System.out.println(demo.add(2.5,3)); //method 3 called } } In the above example, there are four versions of add methods. The first method takes two parameters while the second one takes three. For the third and fourth methods there is a change of order of parameters. The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time. 3.8.2 Dynamic Polymorphism Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called. Have a look at the following example. class Vehicle { public void move() { DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 22
  23. 23. TRAINING REPORT CORE JAVA System.out.println(“Vehicles can move!!”); } } class MotorBike extends Vehicle { public void move() { System.out.println(“MotorBike can move and accelerate too!!”); } } class Test { public static void main(String[] args) { Vehicle vh=new MotorBike(); vh.move(); // prints MotorBike can move and accelerate too!! vh=new Vehicle(); vh.move(); // prints Vehicles can move!! } } It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference. In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called. As the method to call is determined at runtime, this is called dynamic binding or late binding. 3.8.3 Overloading Now let’s continue to discuss overloading and overriding. I have shown an image of a overloaded truck. I specifically used this image and drawn a wrong mark on it. Because, when I did some research on this topic using internet almost all web pages where ever DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 23
  24. 24. TRAINING REPORT CORE JAVA overloading is discussed this kind of overloaded truck image is used to explain the meaning. Please get it right. Overloading is not adding more and more attributes and interfaces to the object so that it looks bulkier. In fact, when we use overloading for the outsiders view the object will look compact. That is putting more behaviour with same interface. That is our object will look sleek. Fig: 3.1 An example Before Overloading Fig: 3.2 An example after Overloading I have shown two images, one is Harmonium, a classical music instrument from India. Just for understanding it is a very trimmed version of piano. The other is a modern digital keyboard. Harmonium is without overloading and keyboard is after overloading. In a digital keyboard, keys are the interface, in programming method name. Speaker is the output, in programming return type of the method. When the player presses the keys he gives input to the method and gets output as music through the speakers. When different input is given we get different output. Here the interface (method name, keys) is same and output type is same. But the actual input (arguments, key press sequence) and output (returned data, music) is different. This is overloading. Look at the whole object (keyboard), how sleek it is after overloading. Example: public class OverloadExample { public static void main(String args[]) { System.out.println(playMusic("C sharp","D sharp")); System.out.println(playMusic("C","D flat","E flat")); } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 24
  25. 25. TRAINING REPORT CORE JAVA public static String playMusic(String c, String d) { return c+d; } public static String playMusic(String c, String d, String e){ return c+d+e; } } 3.8.4 Overriding It is very simple and easy to understand. When we inherit an object, we don’t like certain behavior and so we replace it with our own. Note the word replace. Because after overriding the old behavior is completely obsolete. Now look at the image of a monster truck. Here the old small four wheels are replaced with huge wheels to suit the current need. This is overriding. Fig: 3.3 an example of overriding A java private method cannot be overridden because in first place it is not accessible to an inheriting object. Final parameter in the overloaded method, has an interesting behavior. Implicitly every object in Java is extended from Object class. Object has a method named equals. This implementation compares the passed object with the current object and returns true if the reference are same. In String class we don’t want this behavior. Therefore, equals method of the Object class is overridden in String class with its own implementation. Here DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 25
  26. 26. TRAINING REPORT CORE JAVA the behavior is modified to check if the character sequence is same as the compared one and returns true. This is a classic example of overriding. Example: public class BaseClass{ public void methodToOverride() { //Some code here } } public class DerivedClass extends BaseClass{ public void methodToOverride() { //Some new code here } } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 26
  27. 27. TRAINING REPORT CORE JAVA CHAPTER 4 EXCEPTION HANDLING 4.1 Introduction An exception is an event, which occurs during the execution of the program, that an interrupt the normal flow of the program‘s instruction. In other words, Exceptions are generated when a recognized condition, usually an error condition, arises during the execution of a method. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions. For each method that could throw an exception, our code must report to the Java compiler that it could throw that exact exception. The compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception. Exception handling is basically use five keyword as follows:  Try  Catch  Throw  Throws  Finally 4.2 Overview Exceptions are generated when an error condition occur during the execution of a method. It is possible that a statement might throw more than one kind of exception. Exception can be generated by Java-runtime system or they can be manually generated by code. ErrorHandling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as  Run out of memory  Resource allocation Error  Inability to find a file  Problems in Network connectivity 4.3 Exception and exception handling DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 27
  28. 28. TRAINING REPORT CORE JAVA Exceptions are generated when a recognized an error condition during the execution of a program. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions  for each method that could throw an exception, our code must report to the Java compiler that it could throw that exact exception.  the compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception. There are two ways to handle an exception:  we can try the "risky" code, catch the exception, and do something about it, after which the transmission of the exception come to an end.  we can mark that this method throws that exception, in which case the Java runtime engine will throw the exception back to the method. So, if we use a method in our code that is marked as throwing a particular exception, the compiler will not allow that code unless we handle the exception. If the exception occurs in a try block, the JVM looks to the catch block(s) that follow to see if any of them equivalent the exception type. The first one that matches will be executed. If none match, then this methods ends, and execution jumps to the method that called this one, at the point the call was made. Fig: 4.1 a partial view of the Throwable family DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 28
  29. 29. TRAINING REPORT CORE JAVA 4.4 Try…catch If a method is going to resolve potential exception internally, the line of code that could generate the exception is placed inside a try block. There may be other code inside the try block, before and/or after the risky line(s) - any code that depends upon the risky code's success should be in the try block, since it will automatically be skipped if the exception occurs. Syntax: try { code risky/unsafe code code that depends on the risky code succeeding } There is usually at least one catch block immediately after the try block. A catch block must specify what type of exception it will catch. Syntax: catch (ExceptionClassName exceptionObjectName) { code using methods from exceptionObjectName } There can be more than one catch block, each one marked for a correct exception class. The exception class that is caught can be any class in the exception hierarchy, either a general (base) class, or a very correct (derived) class. The catch block(s) must handle all checked exceptions that the try block is known to throw unless we want to throw that exception back to the method. It is possible to have a try block without any catch blocks if we have a finally block but any checked exceptions still need to be caught, or the method needs to declare that it throws them. If an exception occurs within a try block, execution jumps to the first catch block whose exception class matches the exception that occurred. Any steps remaining in the try block are skipped. If no exception occurs, then the catch blocks are skipped If declare a variable within a try block, it will not exist outside the try block, since the curly braces define the scope of the variable. We will often need that DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 29
  30. 30. TRAINING REPORT CORE JAVA variable later, if nowhere else other than the catch or finally blocks, so we would need to declare the variable before the try. If we declare but don't initialize a variable before a try block, and the only place we set a value for that variable is in the try block, then it is possible when execution leaves the try ... catch structure that the variable never received a value. So, we would get a "possibly uninitialized value" error message from the compiler, since it actually keeps track of that sort of thing.Example: public class demo { public static void main(String[] args) { int ans1, ans2; int a = 2, b = 2, c = 0; try { ans1 = a/b; System.out.println("a/b = " + ans1); ans2 = a/c; System.out.println("a/c = " + ans2); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception!"); } System.out.println("demo is over"); } } 4.5 Throw We can throw an exception explicitly using the throw statement. For example we need to throw an exception when a user enters a wrong student ID or password. The throws clause is used to list the types of exception that can be thrown in the execution of a method in a program. The throw statement causes termination of the normal flow of control of the java DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 30
  31. 31. TRAINING REPORT CORE JAVA code and prevents the execution of the subsequent statements. The throw clause convey the control to the nearest catch block handling the type of exception object throws. If no such catch block exists, the program terminates. The throw statement accepts a single argument, which is an object of the Exception class. Syntax: throw ThrowableObj We can use the following code to throw the IllegalStateException exception: class demo { static void tdemo() { try { throw new IllegalStateException (); } catch (NullPointerException e) { System.out.println ("Not Caught by the catch block inside tdemo ()."); } } public static void main (String args[ ]) { try { tdemo(); } catch(IllegalStateException e) { System.out.println("Exception Caught in:"+e); } } } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 31
  32. 32. TRAINING REPORT CORE JAVA 4.5 Throws The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method. This is done using the throws statement. The throws clause lists the types of exceptions that a method might throw. Syntax: [< access specifier >] [< modifier >] < return type > < method name > [< arg list >] [ throws <exception list >] We can use the following code to use the throws statement. class demo { static void throwMethod ( ) throws ClassNotFoundException { System.out.println ("In throwMethod "); throw new ClassNotFoundException ( ); } public static void main (String args [ ]) { try { throwMethod ( ); } catch ( ClassNotFoundException e) { System.out.println (" throwMethod has thrown an Exception :" +e); } } } 4.6 Finally DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 32
  33. 33. TRAINING REPORT CORE JAVA To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try and catch blocks. The code in the finally block will almost always execute, even if an unhandled exception occurs; in fact, even if a return statement is encountered. If an exception causes a catch block to execute, the finally block will be executed after the catch block or if an uncaught exception occurs, the finally block executes, and then execution exits this method nand the exception is thrown to the method that called this method. Syntax: try { risky code/ unsafe code block } catch (ExceptionClassName exceptionObjectName) { code to resolve problem } finally { code that will always execute } Example: public class demo { public static void main(String args[]) { try { System.out.println("Try Block before the error."); System.out.println(1/0); System.out.println("Try Block after the error."); } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 33
  34. 34. TRAINING REPORT CORE JAVA catch(java.lang.ArithmeticException e) { System.out.println("Catch Block"); System.out.println("A Stack Trace of the Error:"); e.printStackTrace(); //e.getMessage(); System.out.println("The operation is not possible."); } finally { System.out.println("Finally Block"); } System.out.println("demo is over"); } } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 34
  35. 35. TRAINING REPORT CORE JAVA CHAPTER 5 MULTI-THREADING 5.1 The java thread model Thread is a sequential path of execution of a program. In java we can create multiple threads for the full utilization of the processor time. Java environment has been built around the multithreading model. In fact all java class libraries have been designed keeping multithreading in mind. If a thread goes off to sleep for some time, the rest program does not get affected by this. Similarly, an animation loop can be fired that will not stop the working of rest of the system. At a point of time a thread can be in any one of the following states: new, ready, running, inactive and finished. A thread enters the new state as soon as it is created. When it is started, it is ready to run. The start() method in turn calls the run() method which makes the thread enter the running state. While running, a thread might get blocked because some resource that it requires is not available, or it could be suspended on purpose for some reason. In such a case the thread enters the state of being inactive. A thread can also be stopped purposely because its time has been expired, then it enters the state of ready to run once again. A thread that is in running state can be stopped once its job has finished. A thread that is in inactive state can either be resumed, in which case it enters the ready state again, or it can be stopped in which case it enters the finished state. 5.2 Multithreading Multithreading is a process of executing multiple threads simultaneously. So at this point we will ask ourselves what a thread is. A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process. So in short, Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode on a single processor system. Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes. I need to define another term related to threads: process: A process consists of the memory space allocated DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 35
  36. 36. TRAINING REPORT CORE JAVA by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time. Fig: 5.1 an example of multithreading In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread. 5.3 Thread Priorities Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). Threads with higher priority are more important to a program and should be allocated processor time before lower -priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent. 5.4 Creating Thread Java defines two ways in which this can be accomplished:  You can implement the Runnable interface.  You can extend the Thread class itself. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 36
  37. 37. TRAINING REPORT CORE JAVA 5.4.1 Implementing the java.lang.Runnable Interface The procedure for creating threads by implementing the Runnable Interface is as follows:  A Class implements the Runnable Interface, override the run() method to define the code executed by thread. An object of this class is Runnable Object.  Create an object of Thread Class by passing a Runnable object as argument.  Invoke the start( ) method on the instance of the Thread class. The following program demonstrates the thread creation implementing the Runnable interface: class MyThread1 implements Runnable{ Thread t; String s=null; MyThread1(String s1){ s=s1; t=new Thread(this); t.start(); } public void run(){ System.out.println(s); } } public class RunableThread{ public static void main(String args[]){ MyThread1 m1=new MyThread1("Thread started...."); } } There are two reasons for implementing a Runnable interface preferable to extending the Thread class: 1. If you extend the Thread Class, that means that subclass cannot extend any other Class, but if you implement Runnable interface then you can do this. 2. The class implementing the Runnable interface can avoid the full overhead of Thread class which can be excessive. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 37
  38. 38. TRAINING REPORT CORE JAVA 5.4.2 Extending the java.lang.Thread Class For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps:  Extend the java.lang.Thread Class.  Override the run( ) method in the subclass from the Thread class to define the code executed by the thread.  Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor.  Invoke the start( ) method on the instance of the class to make the thread eligible for running. The following program demonstrates a single thread creation extending the "Thread" Class: class MyThread extends Thread{ String s=null; MyThread(String s1){ s=s1; start(); } public void run(){ System.out.println(s); } } public class RunThread{ public static void main(String args[]){ MyThread m1=new MyThread("Thread started...."); } } 5.5 Basic control of thread 5.5.1 Test thread Syntax: Is Alive() DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 38
  39. 39. TRAINING REPORT CORE JAVA 5.5.2 Access thread Syntax: getPriority() setPriority() 5.5.3 Put thread on hold Syntax: Thread.sleep() //static method Join() Thread.yield() //static method 5.5.4 The join method Syntax: Public static void main(String args[]) { Thread t=new Thread(new Runner()); t.start(); // Do stuff in parallel with the order thread for a while // Wait here for the other thread to finish Try { t.join(); } catch (InterruptedException e) { // the other thread came back early } // Now continue in this thread } DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 39
  40. 40. TRAINING REPORT CORE JAVA CHAPTER 6 STREAM 6.1 Stream A stream is a path of communication between the source of some information and its destination. That information, an un-interpreted byte stream, can come from any “pipe source,” the computer’s memory, or even from the Internet. In fact, the source and destination of a stream are completely arbitrary producers and consumers of bytes, respectively. Therein lies the power of the abstraction. You don’t need to know about the source of the information when reading from a stream, and you don’t need to know about the final destination when writing to one. General-purpose methods that can read from any source accept a stream argument to specify that source; general methods for writing accept a stream to specify the destination. Arbitrary processors (or filters) of data have two stream arguments. They read from the first, process the data, and write the results to the second. These processors have no idea of either the source or the destination of the data they are processing. Sources and destinations can vary widely: from two memory buffers on the same local computer, to the ELF transmissions to and from a submarine at sea, to the realtime data streams of a NASA probe in deep space. By decoupling the consuming, processing, or producing of data from the sources and destinations of that data, you can mix and match any combination of them at will as you write your program. In the future, when new, previously nonexistent forms of source or destination (or consumer, processor, or producer) appear, they can be used within the same framework, with no changes to your classes. New stream abstractions, supporting higher levels of interpretation “on top of” the bytes, can be written completely independently of the underlying transport mechanisms for the bytes themselves. At the pinnacle of this stream framework are the two abstract classes, InputStream and OutputStream. If you turn briefly to the diagram for in Appendix B, These classes is a virtual cornucopia of categorized classes, demonstrating the wide range of streams in the system, but also demonstrating an extremely well-designed hierarchy of relationships between these streams, one well worth learning from. Let’s begin with the parents and then work our way down this bushy tree. There are two types of Streams in java , InputStream and OutputStream. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 40
  41. 41. TRAINING REPORT CORE JAVA 6.2 Input Streams All the methods you will explore today are declared to throw IOExceptions. This new subclass of Exception conceptually embodies all the possible I/O errors that might occur while using streams. Several subclasses of it define a few, more specific exceptions that can be thrown as well. For now, it is enough to know that you must either catch an IOException, or be in a method that can “pass it along,” to be a well-behaved user of streams. 6.2.1 read() The most important method to the consumer of an input stream is the one that reads bytes from the source. This method, read(), comes in many flavors, and each is demonstrated in an example in today’s lesson. Each of these read()methods is defined to “block” (wait) until all the input requested becomes available. Don’t worry about this limitation; because of multithreading, you can do as many other things as you like while this one thread is waiting for input. In fact, it is a common idiom to assign a thread to each stream of input (and for each stream of output) that is solely responsible for reading from it (or writing to it). These input threads might then “hand off” the information to other threads for processing. This naturally overlaps the I/O time of your program with its compute time. Here’s the first form of read(): InputStream s = getAnInputStreamFromSomewhere(); byte[] buffer = new byte[1024]; // any size will do if ( != buffer.length) System.out.println(“I got less than I expected.”); This form of read()attempts to fill the entire buffer given. If it cannot (usually due to reaching the end of the input stream), it returns the actual number of bytes that were read into the buffer. After that, any further calls to read()return -1, indicating that you are at the end of the stream. Note that the ifstatement still works even in this case, because -1! = 1024(this corresponds to an input stream with no bytes in it all). 6.2.2 skip() What if you want to skip over some of the bytes in a stream, or start reading a stream from other than its beginning? A method similar to read()does the trick: DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 41
  42. 42. TRAINING REPORT CORE JAVA if (s.skip(1024) ! = 1024) System.out.println(“I skipped less than I expected”); This skips over the next 1024bytes in the input stream. skip()takes and returns a long integer, because streams are not required to be limited to any particular size. The default implementation of skip in this release simply uses read(): public long skip(long n) throws IOException { byte[] buffer = new byte[(int) n]; return read(buffer); } 6.2.3 available() If for some reason we would like to know how many bytes are in the stream right now, we can ask: if (s.available() < 1024) System.out.println(“Too little is available right now.”); This tells we the number of bytes that we can read() without blocking. Because of the abstract nature of the source of these bytes, streams may or may not be able to tell you a reasonable answer to this question. For example, some streams always return 0. Unless you use specific subclasses of InputStream that you know provide a reasonable answer to this question, it’s not a good idea to rely upon this method. Remember, multithreading eliminates many of the problems associated with blocking while waiting for a stream to fill again. Thus, one of the strongest rationales for the use of available() goes away. 6.2.4 mark() and reset() Some streams support the notion of marking a position in the stream, and then later resetting the stream to that position to reread the bytes there. Clearly, the stream would have to “remember” all those bytes, so there is a limitation on how far apart in a stream the mark and its subsequent reset can occur. There’s also a method that asks whether or not the stream supports the notion of marking at all. Here’s an example: InputStream s = getAnInputStreamFromSomewhere(); if (s.markSupported()) { // does s support the notion? DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 42
  43. 43. TRAINING REPORT CORE JAVA . . . // read the stream for a while s.mark(1024); . . . // read less than 1024 more bytes s.reset(); . . . // we can now re-read those bytes } else { . . . // no, perform some alternative } When marking a stream, you specify the maximum number of bytes you intend to allow to pass before resetting it. This allows the stream to limit the size of its byte “memory.” If this number of bytes goes by and you have not yet reset(), the mark becomes invalid, and attempting to reset()will throw an exception. Marking and resetting a stream is most valuable when you are attempting to identify the type of the stream (or the next part of the stream), but to do so, you must consume a significant piece of it in the process. Often, this is because you have several black-box parsers that you can hand the stream to, but they will consume some (unknown to you) number of bytes before making up their mind about whether the stream is of their type. Set a large size for the read limit above, and let each parser run until it either throws an error or completes a successful parse. If an error is thrown, reset()and try the next parser. 6.2.5 close() Because you don’t know what 531sources an open stream rep531sents, nor how to deal with them properly when you’re finished reading the stream, you must usually explicitly close down a stream so that it can release these 531sources. Of course, garbage collection and a finalization method can do this for you, but what if you need to reopen that stream or those resources before they have been freed by this asynchronous p5ocess? At best, this is annoying or confusing; at worst, it introduces an unexpected, obscure, and difficult-totrack-down bug. Because you’re interacting with the outside world of external 531sources, it’s safer to be explicit about when you’re finished using them: InputStream s = alwaysMakesANewInputStream(); try { DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 43
  44. 44. TRAINING REPORT CORE JAVA . . . // use s to your heart’s content } finally { s.close(); } Get used to this idiom (using finally); it’s a useful way to be sure something (such as closing the stream) always gets done. Of course, you’re assuming that the stream is always successfully created. If this is not always the case, and nullis sometimes returned instead, here’s the correct way to be safe: InputStream s = tryToMakeANewInputStream(); if (s != null) { try { ... } finally { s.close(); } } All input streams descend from the abstract class InputStream. 6.3 Output Stream Output streams are, in almost every case, paired with a “brother” InputStream that you’ve already learned. If an InputStream performs a certain operation, the “brother” OutputStream performs the inverse operation. 6.3.1 write() The most important method to the producer of an output stream is the one that writes bytes to the destination. This method, write(), comes in many flavors, each demonstrated in an example below. OutputStream s = getAnOutputStreamFromSomewhere(); byte[] buffer = new byte[1024]; // any size will do fillInData(buffer); // the data we want to output s.write(buffer); DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 44
  45. 45. TRAINING REPORT CORE JAVA You also can write a “slice” of your buffer by specifying the offset into the buffer, and the length desired, as arguments to write(): s.write(buffer, 100, 300); This writes out bytes 100through 399and behaves otherwise exactly the same as the previous write() method. In fact, in the current release, the default implementation of the former version of write()uses the latter: public void write(byte[] buffer) throws IOException { write(buffer, 0, buffer.length); } Finally, you can write out bytes one at a time: while (thereAreMoreBytesToOutput()) { byte b = getNextByteForOutput(); s.write(b); } 6.3.2 flush() Because you don’t know what an output stream is connected to, you might be required to “flush” your output through some buffered cache to get it to be written (in a timely manner, or at all). OutputStream’s version of this method does nothing, but it is expected that subclasses that require flushing (for example, BufferedOutputStream and PrintStream) will override this version to do something nontrivial. 6.3.3 close() Just like for an InputStream, you should (usually) explicitly close down an OutputStream so that it can release any resources it may have reserved on your behalf. (All the same notes and examples from InputStream’s close() method apply here, with the prefix In replaced everywhere by Out.) All output streams descend from the abstract class OutputStream. All share the previous few methods in common. DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING 45