DATA TYPES
UNIT IINTRODUCTION TO OOP AND JAVA FUNDAMENTALSObject Oriented Programming - Abstraction – objects and classes - Encapsulation- Inheritance - Polymorphism- OOP in Java – Characteristics of Java – The Java Environment - Java Source File -Structure – Compilation. Fundamental Programming Structures in Java – Defining classes in Java – constructors, methods -access specifiers - static members -Comments, Data Types, Variables, Operators, Control Flow, Arrays , Packages - JavaDoc comments. OBJECT ORIENTED PROGRAMMING Object-oriented programming (or OOP for short) is the dominant programming paradigm these days, having replaced the “structured,” procedural programming techniques that were developed in the 1970s. Java is totally object oriented, and you have to be familiar with OOP to become productive with Java. An object-oriented program is made of objects. Each object has a specific functionality that is exposed to its users, and a hidden implementation. Many objects in your programs will be taken “off-the-shelf” from a library; others are custom designed. Whether you build an object or buy it might depend on your budget or on time. Traditional structured programming consists of designing a set of procedures (or algorithms) to solve a problem. After the procedures were determined, the traditional next step was to find appropriate ways to store the data. ABSTRACTION An essential element of object oriented programming is abstraction. Humans manage complexity through abstraction. A powerful way to manage abstraction is through the use of hierarchical classifications.OBJECTS AND CLASSES ClassesA class is the template or blueprint from which objects are made. Thinking about classes as cookie cutters. Objects are the cookies themselves. When you construct an object from a class, you are said to have created an instance of the class.As you have seen, all code that you write in Java is inside a class. The standard Java library supplies several thousand classes for such diverse purposes as user interface design, dates and calendars, and network programming. Nonetheless, you still have to create your own classes in Java to describe the objects of the problem domains of your applications.ObjectsTo work with OOP, you should be able to identify three key characteristics of objects:? The object’s behavior—What can you do with this object, or what methods can you apply to it?? The object’s state—How does the object react when you apply those methods?? The object’s identity—How is the object distinguished from others that may have the same behavior and state?All objects that are instances of the same class share a family resemblance by supporting the same behavior. The behavior of an object is defined by the methods that you can call.However, the state of an object does not completely describe it, because each object has a distinct identity. For example, in an order-processing system, two orders are distinct even if they request identical items. Notice that the individual objects that are instances of a class always differ in their identity and usually differ in their state.ENCAPSULATIONEncapsulation (sometimes called information hiding) is a key concept in working with objects. Formally, encapsulation is nothing more than combining data and behavior in one package and hiding the implementation details from the user of the object. The data in an object are called its instance fields, and the procedures that operate on the data are called its methods. A specific object that is an instance of a class will have specific values for its instance fields. The set of those values is the current state of the object. The key to making encapsulation work is to have methods never directly access instance fields in a class other than their own. Programs should interact with object data only through the object’s methods. Encapsulation is the way to give the object its “black box” behavior, which is the key to reuse and reliability. INHERITANCE The keyword extends indicates that you are making a new class that derives from an existing class. The existing class is called the superclass, base class, or parent class. The new class is called the subclass, derived class, or child class. The terms superclass and subclass are those most commonly used by Java programmers, although some programmers prefer the parent/child analogy, which also ties in nicely with the “inheritance” theme. The Employee class is a superclass, but not because it is superior to its subclass or contains more functionality. In fact, the opposite is true: subclasses have more functionality than their superclasses.POLYMORPHISMThe fact that an object variable (such as the variable e) can refer to multiple actual types is called polymorphism. Automatically selecting the appropriate method at runtime iscalled dynamic binding.OOP IN JAVA All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism. Let’s take a look at these concepts now.Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface.Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. As mentioned earlier, most knowledge is made manageable by hierarchical (that is, top-down) classifications. For example, a Golden Retriever is part of the classification dog, which in turn is part of the mammal class, which is under the larger class animal.Polymorphism (from the Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation.CHARACTERISTICS OF JAVA ■ Secure■ Portable■ Object-oriented■ Robust■ Multithreaded■ Architecture-neutral■ Interpreted■ High performance■ Distributed■ DynamicTHE JAVA ENVIRONMENT The descriptions that follow use the standard Java 2 SDK (Software Development Kit), which is available from Sun Microsystems. If you are using a different Java development environment, then you may need to follow a different procedure for compiling and executing Java programsJAVA SOURCE FILE For most computer languages, the name of the file that holds the source code to a program is arbitrary. However, this is not the case with Java. The first thing that you must learn about Java is that the name you give to a source file is very important. For this example, the name of the source file should be Example.java. In Java, a source file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension. As you can see by looking at the program, the name of the class defined by the program is also Example. This is not a coincidence. In Java, all code must reside inside a class. By convention, the name of that class should match the name of the file that holds the program. STRUCTURE /*This is a simple Java program.Call this file "Example.java".*/class Example {// Your program begins with a call to main().public static void main(String args[]) {System.out.println("This is a simple Java program.");}}COMPILATIONTo compile the Example program, execute the compiler, javac, specifying the name ofthe source file on the command line, as shown here:C:\>javac Example.javaThe javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the Java bytecode is the intermediate representation of your program that contains instructions the Java interpreter will execute. Thus, the output of javac is not code that can be directly executed.To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Example as a command-line argument, as shown here:C:\>java ExampleWhen the program is run, the following output is displayed:This is a simple Java program.When Java source code is compiled, each individual class is put into its own output file named after the class and using the .class extension. This is why it is a good idea to give your Java source files the same name as the class they contain—the name of the source file will match the name of the .class file. When you execute the Java interpreter as just shown, you are actually specifying the name of the class that you want the interpreter to execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it will execute the code contained in the specified class.FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA DEFINING CLASSES IN JAVA public class MyFirstJavaProgram { public static void main(String []args) { System.out.println("Hello World"); }} CONSTRUCTORSFirst Steps with ConstructorsLet’s look at the constructor listed in our Employee class.public Employee(String n, double s, int year, int month, int day){name = n;salary = s;GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);hireDay = calendar.getTime(); }There is an important difference between constructors and other methods. A constructor can only be called in conjunction with the new operator. You can’t apply a constructor to an existing object to reset the instance fields. For example,james.Employee("James Bond", 250000, 1950, 1, 1); // ERROR is a compile-time error.We have more to say about constructors later in this chapter. For now, keep the following in mind:? A constructor has the same name as the class.? A class can have more than one constructor.? A constructor can take zero, one, or more parameters.? A constructor has no return value.? A constructor is always called with the new operator.The constructor declares local variables name and salary. These variables are only accessible inside the constructor. They shadow the instance fields with the same name. Some programmers—such as the authors of this book—write this kind of code when they type faster than they think, because their fingers are used to adding the data type. This is a nasty error that can be hard to track down. You just have to be careful in all of your methods that you don’t use variable names that equal the names of instance fields.Implicit And Explicit ParametersMethods operate on objects and access their instance fields. For example, the methodpublic void raiseSalary(double byPercent){double raise = salary * byPercent / 100;salary += raise;}sets a new value for the salary instance field in the object on which this method isinvoked. Consider the call number007.raiseSalary(5);The effect is to increase the value of the number007.salary field by 5%. More specifically, the call executes the following instructions:double raise = number007.salary * 5 / 100;number007.salary += raise;The raiseSalary method has two parameters. The first parameter, called the implicit parameter, is the object of type Employee that appears before the method name. The second parameter, the number inside the parentheses after the method name, is an explicit parameter. As you can see, the explicit parameters are explicitly listed in the method declaration, for example, double byPercent. The implicit parameter does not appear in the method declaration.METHODSStatic Fields and MethodsIn all sample programs that you have seen, the main method is tagged with the static modifier. We are now ready to discuss the meaning of this modifier.Static FieldsIf you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. For example, let’s suppose we want to assign a unique identification number to each employee. We add an instance field id and a static field nextId to the Employee class:class Employee{. . .private int id;private static int nextId = 1;}Every employee object now has its own id field, but there is only one nextId field that is shared among all instances of the class. Let’s put it another way. If there are 1,000 objects of the Employee class, then there are 1,000 instance fields id, one for each object. But there is a single static field nextId. Even if there are no employee objects, the static field nextId is present. It belongs to the class, not to any individual object.NOTE: In most object-oriented programming languages, static fields are called class fields.The term “static” is a meaningless holdover from C++.Let’s implement a simple method:public void setId(){id = nextId;nextId++;}Suppose you set the employee identification number for harry:harry.setId();Then, the id field of harry is set to the current value of the static field nextId, and the value of the static field is incremented:harry.id = Employee.nextId;Employee.nextId++;Static ConstantsStatic variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant:public class Math{. . .public static final double PI = 3.14159265358979323846;. . .}As we mentioned several times, it is never a good idea to have public fields, because everyone can modify them. However, public constants (that is, final fields) are fine. Because out has been declared as final, you cannot reassign another print stream to it:System.out = new PrintStream(. . .); // ERROR--out is finalACCESS SPECIFIERSClass-Based Access PrivilegesYou know that a method can access the private data of the object on which it is invoked. What many people find surprising is that a method can access the private data of all objects of its class. For example, consider a method equals that compares two employees.class Employee{. . .boolean equals(Employee other){return name.equals(other.name);}}A typical call is if(harry.equals(boss)) . . .This method accesses the private fields of harry, which is not surprising. It also accesses the private fields of boss. This is legal because boss is an object of type Employee, and a method of the Employee class is permitted to access the private fields of any object of type Employee.Private MethodsWhen implementing a class, we make all data fields private because public data are dangerous. But what about the methods? While most methods are public, private methods are used in certain circumstances. Sometimes, you may wish to break up the code for a computation into separate helper methods. Typically, these helper methods should not become part of the public interface—they may be too close to the current implementation or require a special protocol or calling order. Such methods are best implemented as private.To implement a private method in Java, simply change the public keyword to private.By making a method private, you are under no obligation to keep it available if you change to another implementation. The method may well be harder to implement or unnecessary if the data representation changes: this is irrelevant. The point is that as long as the method is private, the designers of the class can be assured that it is never used outside the other class operations and can simply drop it. If a method is public, you cannot simply drop it because other code might rely on it.Final Instance FieldsYou can define an instance field as final. Such a field must be initialized when the object is constructed. That is, it must be guaranteed that the field value has been set after the end of every constructor. Afterwards, the field may not be modified again. For example, the name field of the Employee class may be declared as final because it never changes after the object is constructed—there is no setName method.class Emplyee{. . .private final String name;}The final modifier is particularly useful for fields whose type is primitive or an immutable class. (A class is immutable if none of its methods ever mutate its objects. For example, the String class is immutable.) For mutable classes, the final modifier is likely to confuse the reader. For example, private final Date hiredate;merely means that the object reference stored in the hiredate variable doesn’t get changed after the object is constructed. That does not mean that the hiredate object is constant. Any method is free to invoke the setTime mutator on the object to which hiredate refers.Protected Access As you know, fields in a class are best tagged as private, and methods are usually tagged as public. Any features declared private won’t be visible to other classes. As we said at the beginning of this chapter, this is also true for subclasses: a subclass cannot access the private fields of its superclass.There are times, however, when you want to restrict a method to subclasses only or, less commonly, to allow subclass methods to access a superclass field. In that case, you declare a class feature as protected. For example, if the superclass Employee declares the hireDay field as protected instead of private, then the Manager methods can access it directly. However, the Manager class methods can peek inside the hireDay field of Manager objects only, not of other Employee objects. This restriction is made so that you can’t abuse the protected mechanism and form subclasses just to gain access to the protected fields.STATIC MEMBERSStatic Fields and MethodsIn all sample programs that you have seen, the main method is tagged with the static modifier. We are now ready to discuss the meaning of this modifier.Static FieldsIf you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. For example, let’s suppose we want to assign a unique identification number to each employee. We add an instance field id and a static field nextId to the Employee class:class Employee{. . .private int id;private static int nextId = 1;}Every employee object now has its own id field, but there is only one nextId field that is shared among all instances of the class. Let’s put it another way. If there are 1,000 objects of the Employee class, then there are 1,000 instance fields id, one for each object. But there is a single static field nextId. Even if there are no employee objects, the static field nextId is present. It belongs to the class, not to any individual object.NOTE: In most object-oriented programming languages, static fields are called class fields.The term “static” is a meaningless holdover from C++.Let’s implement a simple method:public void setId(){id = nextId;nextId++;}Suppose you set the employee identification number for harry:harry.setId();Then, the id field of harry is set to the current value of the static field nextId, and the value of the static field is incremented:harry.id = Employee.nextId;Employee.nextId++;Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression Math.pow(x, a)computes the power xa. It does not use any Math object to carry out its task. In other words, it has no implicit parameter. You can think of static methods as methods that don’t have a this parameter “Implicit and Explicit Parameters”) Because static methods don’t operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. You use static methods in two situations:? When a method doesn’t need to access the object state because all neededparameters are supplied as explicit parameters (example: Math.pow)? When a method only needs to access static fields of the class (example:Employee.getNextId)COMMENTSThere are three types of comments defined by Java. You have alreadyseen two: single-line and multiline. The third type is called a documentation comment.This type of comment is used to produce an HTML file that documents your program.The documentation comment begins with a /** and ends with a */. DATA TYPESData 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 you to select the type appropriate to the needs of the application.Data types in Java are classified into two types:Primitive—which include Integer, Character, Boolean, and Floating Point.Non-primitive—which include Classes, Interfaces, and Arrays.PRIMITIVE DATA TYPES1. IntegerInteger 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.TypeSizeRange of values that can be storedbyte1 byte?128 to 127short2 bytes?32768 to 32767int4 bytes?2,147,483,648 to 2,147,483,647long8 bytes9,223,372,036,854,775,808 to9,223,372,036,854,755,8072. Floating PointFloating 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 storedfloat 4 bytes 3.4e?038 to 3.4e+038double 8 bytes 1.7e?308 to 1.7e+0383. CharacterIt 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. BooleanBoolean data types are used to store values with two states: true or false.VARIABLESThere are different types of variables in Java. They are as follows: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. 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 numGears = 6; would create such a static field.3. Local VariablesA 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. 4. ParametersThey are the variables that are passed to the methods of a class.Variable DeclarationIdentifiers 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.Syntax for variable declarationdatatype1 variable1, datatype2 variable2, … datatypen variablen;For example:int a, char ch;InitialisationVariables can be assigned values in the following way: Variablename = value;OPERATORSJava provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:Arithmetic OperatorsRelational OperatorsBitwise OperatorsLogical OperatorsAssignment OperatorsMisc OperatorsThe Arithmetic Operators:Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:Assume integer variable A holds 10 and variable B holds 20, then:Show ExamplesOperatorDescriptionExample+Addition - Adds values on either side of the operatorA + B will give 30-Subtraction - Subtracts right hand operand from left hand operandA - B will give -10*Multiplication - Multiplies values on either side of the operatorA * B will give 200/Division - Divides left hand operand by right hand operandB / A will give 2%Modulus - Divides left hand operand by right hand operand and returns remainderB % A will give 0++Increment - Increases the value of operand by 1B++ gives 21--Decrement - Decreases the value of operand by 1B-- gives 19The Relational Operators:There are following relational operators supported by Java languageAssume variable A holds 10 and variable B holds 20, then:OperatorDescriptionExample==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true. !=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true. >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true. <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true. >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true. <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true. The Bitwise Operators:Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows:a = 0011 1100b = 0000 1101-----------------a&b = 0000 1100a|b = 0011 1101a^b = 0011 0001~a? = 1100 0011The following table lists the bitwise operators:Assume integer variable A holds 60 and variable B holds 13 then:Show ExamplesOperatorDescriptionExample&Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100|Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101^Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111>>>Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111The Logical Operators:The following table lists the logical operators:Assume Boolean variables A holds true and variable B holds false, then:Show ExamplesOperatorDescriptionExample&&Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.(A && B) is false. ||Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.(A || B) is true. !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true. The Assignment Operators:There are following assignment operators supported by Java language:Show ExamplesOperatorDescriptionExample=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A<<=Left shift AND assignment operator C <<= 2 is same as C = C << 2>>=Right shift AND assignment operator C >>= 2 is same as C = C >> 2&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2Misc OperatorsThere are few other operators supported by Java Language.Conditional Operator ( ? : ):Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as:variable x = (expression) ? value if true : value if falseFollowing is the example:public class Test { public static void main(String args[]){ int a , b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); }}This would produce the following result:Value of b is : 30Value of b is : 20instanceof Operator:This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceof operator is wriiten as:( Object reference variable ) instanceof (class/interface type)If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example:public class Test { public static void main(String args[]){ String name = "James"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); }}Precedence of Java Operators:Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.Category?Operator?Associativity?Postfix?() [] . (dot operator)Left to right?Unary?++ - - ! ~ Right to left?Multiplicative ?* / %?Left to right?Additive ?+ -?Left to right?Shift ?>> >>> << ?Left to right?Relational ?> >= < <= ?Left to right?Equality ?== !=?Left to right?Bitwise AND?&?Left to right?Bitwise XOR?^?Left to right?Bitwise OR?|?Left to right?Logical AND?&&?Left to right?Logical OR?||?Left to right?Conditional??:?Right to left?Assignment?= += -= *= /= %= >>= <<= &= ^= |=?Right to left?Comma?,?Left to right?CONTROL FLOWJava Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;· Selection statements: if, if-else and switch.· Loop statements: while, do-while and for.· Transfer statements: break, continue, return, try-catch-finally and assert.Selection StatementsThe If StatementThe if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.The If-else StatementThe if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.The if-else statement has the following syntax:if (<conditional expression>)<statement action>else<statement action>Switch Case StatementThe switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block. There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops:while Loopdo...while Loopfor LoopThe while Loop:A while loop is a control structure that allows you to repeat a task a certain number of times.Syntax:The syntax of a while loop is:while(Boolean_expression){ //Statements}When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.The do...while Loop:A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.Syntax:The syntax of a do...while loop is:do{ //Statements}while(Boolean_expression);Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.The for Loop:A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.A for loop is useful when you know how many times a task is to be repeated.Syntax:The syntax of a for loop is:for(initialization; Boolean_expression; update){ //Statements}Enhanced for loop in Java:As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.Syntax:The syntax of enhanced for loop is:for(declaration : expression){ //Statements}Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.The break Keyword:The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.Syntax:The syntax of a break is a single statement inside any loop:break;The continue Keyword:The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.Syntax:The syntax of a continue is a single statement inside any loop: continue;ARRAYSAn array is a data structure that stores a collection of values of the same type. You access each individual value through an integer index. For example, if a is an array of integers, then a[i] is the ith integer in the array. You declare an array variable by specifying the array type—which is the element type followed by []—and the array variable name. For example, here is the declaration of an array a of integers:int[] a;However, this statement only declares the variable a. It does not yet initialize a with an actual array. You use the new operator to create the array.int[] a = new int[100];This statement sets up an array that can hold 100 integers.java.math.BigInteger java.math.BigDecimal Arrays 91NOTE: You can define an array variable either as int[] a; or as int a[];Most Java programmers prefer the former style because it neatly separates the type int[] (integer array) from the variable name. The array entries are numbered from 0 to 99 (and not 1 to 100). Once the array is created, you can fill the entries in an array, for example, by using a loop:int[] a = new int[100];for (int i = 0; i < 100; i++)a[i] = i; // fills the array with 0 to 99CAUTION: If you construct an array with 100 elements and then try to access the element a[100] (or any other index outside the range 0 . . . 99), then your program will terminate with an “array index out of bounds” exception. To find the number of elements of an array, use array.length. For example: for (int i = 0; i < a.length; i++) System.out.println(a[i]);Once you create an array, you cannot change its size (although you can, of course, change an individual array element). If you frequently need to expand the size of an array while a program is running, you should use a different data structure called an array list. The “for each” LoopJava SE 5.0 introduced a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values. The enhanced for loopfor (variable : collection) statement sets the given variable to each element of the collection and then executes the statement (which, of course, may be a block). The collection expression must be an array or an object of a class that implements the Iterable interface, such as ArrayList. For example,for (int element : a)System.out.println(element);prints each element of the array a on a separate line. You should read this loop as “for each element in a”. The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already containsmethods or variables with the same names (such as System.in). Of course, you could achieve the same effect with a traditional for loop:for (int i = 0; i < a.length; i++)System.out.println(a[i]);However, the “for each” loop is more concise and less error prone. (You don’t have to worry about those pesky start and end index values.)NOTE: The loop variable of the “for each” loop traverses the elements of the array, not the index values. The “for each” loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.TIP: There is an even easier way to print all values of an array, using the toString method of the Arrays class. The call Arrays.toString(a) returns a string containing the array elements, enclosed in brackets and separated by commas, such as "[2, 3, 5, 7, 11, 13]". To print the array, simply callSystem.out.println(Arrays.toString(a));Array Initializers And Anonymous ArraysJava has a shorthand to create an array object and supply initial values at the same time. Here’s an example of the syntax at work:int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };Notice that you do not call new when you use this syntax. You can even initialize an anonymous array:new int[] { 17, 19, 23, 29, 31, 37 }This expression allocates a new array and fills it with the values inside the braces. It counts the number of initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable. For example,smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };is shorthand forint[] anonymous = { 17, 19, 23, 29, 31, 37 };smallPrimes = anonymous;NOTE: It is legal to have arrays of length 0. Such an array can be useful if you write a method that computes an array result and the result happens to be empty. You construct an array of length 0 asnew elementType[0]Note that an array of length 0 is not the same as null.Arrays 93Array CopyingYou can copy one array variable into another, but then both variables refer to the same array:int[] luckyNumbers = smallPrimes;luckyNumbers[5] = 12; // now smallPrimes[5] is also 12.If you actually want to copy all values of one array into a new array, you use the copyTo method in the Arrays class:int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);The second parameter is the length of the new array. A common use of this method is to increase the size of an array:luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);The additional elements are filled with 0 if the array contains numbers, false if the array contains boolean values. Conversely, if the length is less than the length of the original array, only the initial values are copied.For example, the following statements, whose result is illustrated in Figure 3–15, set up two arrays and then copy the last four entries of the first array to the second array. The copy starts at position 2 in the source array and copies four entries, starting at position 3 of the target.int[] smallPrimes = {2, 3, 5, 7, 11, 13};int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};System.arraycopy(smallPrimes, 2, luckyNumbers, 3, 4);for (int i = 0; i < luckyNumbers.length; i++)System.out.println(i + ": " + luckyNumbers[i]);smallPrimes =luckyNumbers =2 3 5 7 11 12The output is0: 10011: 10022: 10033: 54: 75: 116: 13Array SortingTo sort an array of numbers, you can use one of the sort methods in the Arrays class: int[] a = new int[10000];Arrays.sort(a).This method uses a tuned version of the QuickSort algorithm that is claimed to be very efficient on most data sets. The Arrays class provides several other convenience methods for arrays that are included in the API notes at the end of this section.The program in Listing 3–7 puts arrays to work. This program draws a random combination of numbers for a lottery game. For example, if you play a “choose 6 numbers from 49” lottery, then the program might print this:Bet the following combination. It'll make you rich!478193044To select such a random set of numbers, we first fill an array numbers with the values 1, 2, . . . , n:int[] numbers = new int[n];for (int i = 0; i < numbers.length; i++)numbers[i] = i + 1;A second array holds the numbers to be drawn:int[] result = new int[k];Now we draw k numbers. The Math.random method returns a random floating-point number that is between 0 (inclusive) and 1 (exclusive). By multiplying the result with n, we obtain a random number between 0 and n – 1.int r = (int) (Math.random() * n);We set the ith result to be the number at that index. Initially, that is just r + 1, but as you’ll see presently, the contents of the numbers array are changed after each draw. result[i] = numbers[r];PACKAGESPackages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.Some of the existing packages in Java are::java.lang - bundles the fundamental classesjava.io - classes for input , output functions are bundled in this packageProgrammers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, annotations are related.Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.Creating a package:When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.The import Keyword:If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.Example:Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class.package payroll;public class Boss{ public void payEmployee(Employee e) { e.mailCheck(); }}The Directory Structure of Packages:Two major results occur when a class is placed in a package:The name of the package becomes a part of the name of the class, as we just discussed in the previous section.The name of the package must match the directory structure where the corresponding bytecode resides.<path-one>\sources\com\apple\computers\Dell.java<path-two>\classes\com\apple\computers\Dell.classBy doing this, it is possible to give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses. The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.Say <path-two>\classes is the class path, and the package name is com.puters, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.Packages other contentsJava PackageJava PackageExample of packageAccessing package By import packagename.*By import packagename.classnameBy fully qualified nameSubpackageSending class file to another directory-classpath switch4 ways to load the class file or jar fileHow to put two public class in a packageStatic ImportPackage classA java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.Here, we will have the detailed learning of creating and using user-defined packages. Advantage of Java PackageJava package is used to categorize the classes and interfaces so that they can be easily maintained.Java package provides access protection.Java package removes naming collision.Simple example of java packageThe package keyword is used to create a package in java.//save?as?Simple.java??package?mypack;??public?class?Simple{???public?static?void?main(String?args[]){??????System.out.println("Welcome?to?package");?????}??}??How to compile java packageIf you are not using any IDE, you need to follow the syntax given below:javac?-d?directory?javafilename??For examplejavac?-d?.?Simple.java??The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot). How to run java package programYou need to use fully qualified name e.g. mypack.Simple etc to run the class. To Compile: javac -d . Simple.javaTo Run: java mypack.SimpleOutput:Welcome to packageThe -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder. How to access package from another package?There are three ways to access the package from outside the package. import package.*;import package.classname;fully qualified name.1) Using packagename.*2) Using packagename.classname3) Using fully qualified nameJAVADOC COMMENTSDocumentation CommentsThe JDK contains a very useful tool, called javadoc, that generates HTML documentation from your source files. In fact, the on-line API documentation that we described in Chapter 3 of the Text Book is simply the result of running javadoc on the source code of the standard Java library.If you add comments that start with the special delimiter /** to your source code, you too can easily produce professional-looking documentation. This is a very nice scheme because it lets you keep your code and documentation in one place. If you put your documentation into a separate file, then you probably know that the code and comments tend to diverge over time. But because the documentation comments are in the same file as the source code, it is an easy matter to update both and run javadoc ment InsertionThe javadoc utility extracts information for the following items:? Packages? Public classes and interfaces? Public and protected methods? Public and protected fieldsChapter 4. Objects and ClassesDocumentation Comments 163Protected features are introduced in Chapter 5, interfaces in Chapter 6.You can (and should) supply a comment for each of these features. Each comment is placed immediately above the feature it describes. A comment starts with a /** and endswith a */.Each /** . . . */ documentation comment contains free-form text followed by tags. A tag starts with an @, such as @author or @param.The first sentence of the free-form text should be a summary statement. The javadoc utility automatically generates summary pages that extract these sentences.In the free-form text, you can use HTML modifiers such as <em>...</em> for emphasis, <code>...</code> for a monospaced “typewriter” font, <strong>...</strong> for strong emphasis,and even <img ...> to include an image. You should, however, stay away from headings<h1> or rules <hr> because they can interfere with the formatting of the document.NOTE: If your comments contain links to other files such as images (for example, diagrams r images of user interface components), place those files into a subdirectory of thedirectory containing the source file named doc-files. The javadoc utility will copy the docfiles directories and their contents from the source directory to the documentation directory. You need to use the doc-files directory in your link, such as <img src="doc-files/uml.png" alt="UML diagram"/>.Class CommentsThe class comment must be placed after any import statements, directly before the classdefinition.Here is an example of a class comment:/*** A <code>Card</code> object represents a playing card, such* as "Queen of Hearts". A card has a suit (Diamond, Heart,* Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 = Jack,* 12 = Queen, 13 = King)*/public class Card{. . .}NOTE: There is no need to add an * in front of every line. For example, the following commentis equally valid:/**A <code>Card</code> object represents a playing card, suchas "Queen of Hearts". A card has a suit (Diamond, Heart,Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 = Jack,12 = Queen, 13 = King).*/However, most IDEs supply the asterisks automatically and rearrange them when the linebreaks change.Method CommentsEach method comment must immediately precede the method that it describes. In additionto the general-purpose tags, you can use the following tags:? @param variable descriptionThis tag adds an entry to the “parameters” section of the current method. Thedescription can span multiple lines and can use HTML tags. All @param tags for onemethod must be kept together.? @return descriptionThis tag adds a “returns” section to the current method. The description can spanmultiple lines and can use HTML tags.? @throws class descriptionThis tag adds a note that this method may throw an exception. Exceptions are thetopic of Chapter 11.Here is an example of a method comment:/*** Raises the salary of an employee.* @param byPercent the percentage by which to raise the salary (e.g. 10 = 10%)* @return the amount of the raise*/public double raiseSalary(double byPercent){double raise = salary * byPercent / 100;salary += raise;return raise;}Field CommentsYou only need to document public fields—generally that means static constants. Forexample:/*** The "Hearts" card suit*/public static final int HEARTS = 1;General CommentsThe following tags can be used in class documentation comments:? @author nameThis tag makes an “author” entry. You can have multiple @author tags, one for each author.? @version textThis tag makes a “version” entry. The text can be any description of the currentversion.The following tags can be used in all documentation comments:? @since textThis tag makes a “since” entry. The text can be any description of the version thatintroduced this feature. For example, @since version 1.7.1165? @deprecated textThis tag adds a comment that the class, method, or variable should no longer beused. The text should suggest a replacement. For example:@deprecated Use <code>setVisible(true)</code> insteadYou can use hyperlinks to other relevant parts of the javadoc documentation, or to externaldocuments, with the @see and @link tags.? @see referenceThis tag adds a hyperlink in the “see also” section. It can be used with both classesand methods. Here, reference can be one of the following:package.class#feature label<a href="...">label</a>"text"The first case is the most useful. You supply the name of a class, method, or variable,and javadoc inserts a hyperlink to the documentation. For example,@see com.horstmann.corejava.Employee#raiseSalary(double)makes a link to the raiseSalary(double) method in the com.horstmann.corejava.Employeeclass. You can omit the name of the package or both the package and class name.Then, the feature will be located in the current package or class.Note that you must use a #, not a period, to separate the class from the method orvariable name. The Java compiler itself is highly skilled in guessing the variousmeanings of the period character, as separator between packages, subpackages,classes, inner classes, and methods and variables. But the javadoc utility isn’t quite as clever, and you have to help it along.If the @see tag is followed by a < character, then you need to specify a hyperlink. You can link to any URL you like. For example:@see <a href="corejava.html">The Core Java home page</a>In each of these cases, you can specify an optional label that will appear as the link anchor. If you omit the label, then the user will see the target code name or URL as the anchor.If the @see tag is followed by a " character, then the text is displayed in the “see also”section. For example:@see "Core Java 2 volume 2"You can add multiple @see tags for one feature, but you must keep them all together.? If you like, you can place hyperlinks to other classes or methods anywhere in any of your documentation comments. You insert a special tag of the form{@link package.class#feature label}anywhere in a comment. The feature description follows the same rules as for the@see tag.Package and Overview CommentsYou place class, method, and variable comments directly into the Java source files, delimited by /** . . . */ documentation comments. However, to generate package comments, you need to add a separate file in each package directory. You have two choices:1. Supply an HTML file named package.html. All text between the tags <body>...</body> is extracted.2. Supply a Java file named package-info.java. The file must contain an initial Javadoc comment, delimited with /** and */, followed by a package statement. It should contain no further code or comments.You can also supply an overview comment for all source files. Place it in a file called overview.html, located in the parent directory that contains all the source files. All text between the tags <body>...</body> is extracted. This comment is displayed when the user selects “Overview” from the navigation ment ExtractionHere, docDirectory is the name of the directory where you want the HTML files to go. Follow these steps:1. Change to the directory that contains the source files you want to document. Ifyou have nested packages to document, such as com.horstmann.corejava, you must be working in the directory that contains the subdirectory com. (This is the directory that contains the overview.html file if you supplied one.)2. Run the commandjavadoc -d docDirectory nameOfPackagefor a single package. Or runjavadoc -d docDirectory nameOfPackage1 nameOfPackage2...to document multiple packages. If your files are in the default package, then instead runjavadoc -d docDirectory *.javaIf you omit the -d docDirectory option, then the HTML files are extracted to the current directory. That can get messy, and we don’t recommend it.The javadoc program can be fine-tuned by numerous command-line options. ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- computers monitors technology solutions dell usa
- erb tutorial q a
- introduction to the deployment guide
- notes on the current nulling
- dell remote access card console redirection
- purchasing agent user s guide veterans affairs
- officer record brief da pam 600 8
- openmanage server administrator security dell
- portable impact