• No results found

Java

N/A
N/A
Protected

Academic year: 2021

Share "Java"

Copied!
162
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

[Long Question 8-10]

Chapter 1

BASICS

2. Explain the Features of Java ? [

Nov / Dec – 2008] , [Oct / Nov – 2009]

Following are the features of JAVA.

1. Simple and powerful

 Java was designed to be easy to learn and use. Since it exposes the inner working of a machine.

 the programmer can perform his desired actions without fear.

 Unlike other programming systems that the provide dozens of complicated ways to perform a simple task

 Java provides a small number of clear ways to achieve a given task. Anyone can master Java with a little bit of programming experience.

If the user already understands the basic concepts of object-oriented programming, learning Java with be much easier.

2. Secure

 Today everyone is worried about safety and security.  Threatening of viruses and system hackers also exists.

 To overcome all these fears Java has safety and security as its key design principle.

 Using Java Compatible Browser, anyone can safely download Java applets without the fear of viral infection or malicious intent.

 Java achieves this protection by confining a Java program to the Java execution environment and by making it inaccessible to other parts of the computer.

 We can download applets with confidence that no harm will be done and no security will be violated.

3. Portable

 The quality of being architecture neutral allows for a great deal of portability.

 However, another aspect of portability is how the hardware interprets arithmetic operations. In C and C++, source code may run slightly differently on different hardware platforms because of different methods of implementing these arithmetic operations.

 In Java, this has been simplified. An integer type in Java, int, is a signed, two‟s complement 32-bit integer.

 A real number, float, is also a 32-bit floating-point number.

 These consistencies make it possible to have the assurance that any result on one computer with Java can be replicated on another.

(3)

 Java gave a clean, usable, realistic approach to objects.

 The object model in Java is simple and easy to extend, while simple types, such as integers.

 float etc, are kept as high-performance non-objects.

5. Robust

 Most programs in use today fail for one of the two reasons:  memory management or exceptional conditions.

 Thus, the ability to create robust programs was given a high priority in the design of Java.

 Java forces the user to find mistakes in the early stages of program development.

 At the same time, Java frees the user from having to worry about many of the most common causes of programming errors.

 Java checks code at compilation time. However, it also checks the code at run time.

 Java virtually rectifies the problem of memory management by managing memory allocation and automatic memory deallocation by providing garbage collection for unused objects.

 Java also handles exceptional conditions by providing object-oriented exceptional handling. In a well-written Java program, all run-time errors can – and should – be managed by the program itself.

6. Multithreaded

 Java was designed to meet the real-world requirements of creating interactive, networked programs to achieve this,

 java supports multithreaded programming, which allows the user to write programs that perform many functions simultaneously

 The Java run-time system enables the user to construct smoothly running interactive systems.

 Java‟s easy-to-use approach to mutithreading allows the user to think about the specific behavior of his-her own program, not the multitasking subsystem.

7. Architecture-neutral

 The Java designers worked hard in achieving their goal “write once; run anywhere, anytime, forever”

 and as a result the Java Virtual Machine was developed.

 A main issue for the Java designers was that of code longevity and portability.

 One of the main problem is the execution speed of the program.

 Since Java is Architecture-neutral it generates bytecode that resembles machine code, and are not specific to any processor.

(4)

8. Interpreted and High performance

 Java enables the creation of cross-platform programs by compiling the code into an intermediate representation called Java bytecode.

 This code can be interpreted on any system that has a Java Virtual Machine.

 Most of the earlier cross-platform solutions are run at the expense of performance.

 Java was designed to perform well on very low-power CPUs.

 Java bytecode was carefully designed so that it can be easily translated into native machine code for very high performance.

9. Distributed

 Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.

 In fact, accessing a resource using a URL (Uniform Resource Locator) is not different from accessing a file.

 This allowed objects on two different computers to execute procedures remotely.

 Java has recently revived these interfaces in a package called Remote Method Invocation (RMI).

10. Dynamic

 Java programs carry with them extensive amounts of run-time information that is used to verify and resolve accesses to objects at run time.

 Using this concept it is possible to dynamically link code.

 Dynamic property of Java adds strength to the applet environment, which are small fragments of bytecode may be dynamically updated on a running system.

/* A program displaying the usage of variable and data types */ class second

{

public static void main (String args[]) {

int x = 90; short y = 4; float z = 10.87f; String name = "Ram";

System.out.println("\n\nThe integer value is " + x); System.out.println("\n\nThe integer value is " + y); System.out.println("\n\nThe integer value is " + z); System.out.println("\n\nThe integer value is " + name); }

(5)

/* Write a program to add, substract, multiply and divide two numbers */ class three

{

public static void main (String args[]) {

int x = 10; int y = 20; float z = 25.98f;

System.out.println("\n\nThe value of x + y is " + (x+y)); System.out.println("\n\nThe value of x - y is " + (z-y)); System.out.println("\n\nThe value of x * y is " + (x*y)); System.out.println("\n\nThe value of x / y is " + (z/y)); System.out.println("\n\nThe value of x % y is " + (z%y)); }

}

3. Types of Flow Controls in java ?

[March/April -2009]

Following statements are used to control the flow of execution in a program. 1. Conditional Statements

 If – else statement  Switch – case statement 2. Looping statements  For loop  While loop  Do – while loop 3. Other statements  Break  Continue 3.1 Conditional Statements 3.1.1 If-else statement a. if (expression) Statement;

 When the expression is true the Statement within the if is executed.

(6)

 If the expression is false then the statement within the if is not executed and the execution continues with the statement after the if statement.

/* This progam finds the largest of three numbers */ class larger1

{

public static void main(String args[]) { int x1 = 15; int x2 = 20; int x3 = 10; int large; large = x1; if (x2 > large) large = x2; if (x3 > large) large = x3;

System.out.println("\n\n\tLargest number = " + large); } } b. if (expression) { Statement 1; Statement 2; }

 Same as in case a, except that here multiple statements are executed if the expression Is true.

 Note that when multiple statements are to be executed when the expression is true, they are enclosed within parentheses.

c. if (expression) Statement 1; Else

Statement 2;

 If the expression is true, execute statement 1, otherwise execute statement 2. After that proceed with the next statement after the if-else statement.

/* This program checks whether the student has passed or not */ class result

{

public static void main(String args[]) {

(7)

if (marks<40)

System.out.println("\nThe student has failed .. "); else

System.out.println("\nThe student has Passed .. "); } } d. if (expression) { Statement 1; Statement 2; } else { Statement 3; Statement 4; }

 Same as in case c, except that here Statement 1 and Statement 2 are executed when the expression is true and Statement 3,

 Statement 4, are executed when the expression is false. /* Program to display the use of if..else..if */

class if1 {

public static void main(String args[]) {

int month = 12; String season;

if (month == 12 || month == 1 || month ==2) {

season = "Winter"; }

else if (month == 3 || month == 4 || month ==5) {

season = "Spring"; }

else if (month == 6 || month == 7 || month ==8) {

season = "Summer"; }

else if (month == 9 || month == 10 || month ==11) {

season = "Autumn"; }

else {

(8)

season = "Invalid month "; }

System.out.println("Arpil is in " + season + "."); }

}

3.1.2 Switch statement

 When a variable value has to be compared with multiple values, we require nested if statements.

 The readability of the nested if statement is poor and hence understanding of the logic becomes difficult. In such cases, switch statement can be used. switch (expression) { case value 1 : statement 1 ; break; case value 2 : statement 2 ; break; case value 3 : statement 3 ; break; default : statement 4 ; break; }

 The test variable or expression to be tested can be any of the primitive types byte, char, short, or int.

 This value is compared with each „case‟ values. If a match is found, the corresponding statement or statements are executed.

 If no match is found, statement or statements in the default case are executed. Default statement is optional.

 If default statement is absent, then if no matches are found, then the switch statement completes without doing anything.

/* An example that shows the usage of switch..case */ class switchuse

{

public static void main(String args[]) { int weekday=3; switch(weekday) { case 1: System.out.println("Sunday") ; break; case 2: System.out.println("Monday") ;

(9)

case 3: System.out.println("Tuesday") ; break; case 4: System.out.println("Wednesday") ; break; case 5: System.out.println("Thursday") ; break; case 6: System.out.println("Friday") ; break; case 7: System.out.println("Saturday") ; break;

default: System.out.println("Not a valid day "); break; } } } 3.2 Looping statements  For loop  While loop  Do- while loop

3.2.1 For loop

 The for loop repeats a set of statements a certain number of times until a condition is matched.

 It is commonly used for simple iteration. The for loop appears as shown below.

Syntax

for (initialization; test; expression) {

Set of statements; }

 In the first part a variable is initialized to a value.

 The second part consists of a test condition that returns only a Boolean value. The last part is an expression, evaluated every time the loop is executed.  The following example depicts the usage of the for loop.

/* An example of for loop */ class for1

{

public static void main(String args[]) {

(10)

for (i=0;i<10;i++) {

System.out.println("\nExample of for loop "); }

} }

3.2.2 The while loop

 The while loop executes a set of code repeatedly until the condition returns false.

 The syntax for the while loop is given below: Syntax

while (<condition>) {

<body of the loop> }

 Where <condition> is the condition to be tested. If the condition returns true then the statements inside the <body of the loop> are executed.

 Else, the loop is not executed. /* An example of while loop */ class while1

{

public static void main(String args[]) { int i=1; while(i<=10) { System.out.println("\n" + i); i++; } } }

3.2.3 The do…while loop

 The do while loop is similar to the while loop except that the condition to be evaluated is given at the end.

 Hence the loop is executed at least once even when the condition is false.  The syntax for the do while loop is as follows:

Syntax do{

<body of the loop> } while (<condition>);

(11)

{

public static void main(String args[]) { int i = 1; int sum = 0; do { sum = sum + i; i++; }while (i<=100);

System.out.println("\n\n\tThe sum of 1 to 100 is .. " + sum); }

}

3.3 Other statements

 Break  Continue

3.3.1 The break statement

 This statement is used to jump out of a loop.

 Break statement was previously used in switch – case statements.

 On encountering a break statement within a loop, the execution continues with the next statement outside the loop.

 The remaining statements which are after the break and within the loop are skipped.

 Break statement can also be used with the label of a statement.  A statement can be labeled as follows.

statementName : SomeJavaStatement

 When we use break statement along with label as break statementName;

 The execution continues with the statement having the label. This is equivalent to a goto statement.

/* An example of break statement */ class break1

{

public static void main(String args[]) {

int i = 1; while (i<=10) {

(12)

System.out.println("\n" + i); i++; if (i==5) { break; } } } }

/* An example of break to a label */ class break3

{

public static void main (String args[]) { boolean t=true; a: { b: { c: {

System.out.println("Before the break"); if(t)

break b;

System.out.println("This will not execute"); }

System.out.println("This will not execute"); } System.out.println("This is after b"); } } } 3.3.2 Continue statement

 This statement is used only within looping statements.

 When the continue statement is encountered, the next iteration starts.

 The remaining statements in the loop are skipped. The execution starts from the top of loop again.

 The program below shows the use of continue statement. /* This is an example of continue */

class continue1 {

public static void main(String args[]) {

for (int i=0; i<10; i++) {

(13)

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

4. Explain Data Types of Java ?

[March/April -2009]

 Java provides several data types that are commonly supported on all platforms. For example,

 the int (integer) data type in Java is represented as 4-bytes in the memory on all machines, irrespective of where the Java programs run.

 Hence, Java programs need not to be modified to run on different platforms. In Java, data types fall under two categories:

 Primitive data types  Reference data types

4.1 Primitive Data Types

Java provides eight primitive data types. Data Type Size in bits Range Explanation

Byte 8 -128 to 127 The byte data type is typically used to store small amount of data in bytes. It is mostly used while handling text files.

Char 16 All characters The char data type is used to store names or character data.

Boolean 1 True or false The Boolean dats type is used to store a true or a false value.

Short 16 -32768 to 32767 The short data type is used to store smaller numbers upto 32767.

Int 32 -2,147,483,648 to +2,2,147,483,647

The int data type is used to store the large number upto 2,147,483,648. Long 64 -9,223,372,036,854,775,808 to

+9,223,372,036,856,775,807

The long data type is used to store very large numbers upto 9,223,372,036,854,775,808

Float 32 -3.40292347E+38 to +3.40292347E+38

The float data type is used to store decimal upto 3.40292347E+38. Double 64 -1.79769313486231570

E+308

+1.79769313486231570 E+308

The double data type is used to store the large number values with decimal upto 1.79769313486231570E+308.

4.2 Composite Data Types

(14)

Data Type Description

Array A collection of several items of the same data type. For example names of student.

Class A collection of variables and methods.

Interface An abstract class created to implement multiple inheritance in JAVA.

Arrays can be declared in three ways:

Way Description Syntax Example

Only Declaration

Just declares the array. Datatype identifier[] Char ch[ ]; declares a character array named ch. Declaration and creation Declares and allocates memory for the array elements using the reserved word „new‟. Datatype identifier[] =new datatype[size]; Char ch[] = new char[10]; declares an array ch to store 10 characters. Declaration, creation and initialization

Declares the array, allocates memory for it and assigns initial values to its elements. Datatype identifier[] = {value1, value2, ….ValueN}; Char ch[] ={„A‟,‟B‟,‟C‟,‟D‟}; declares an array ch to store 4 pre-as signed character values.

/* An example of array outside main function */ class array3 { int i; int da[]={1,2,3,4,5,6,7}; void disp() {

System.out.println("\n\nDisplaying Array Details .. "); for(i=0;i<7;i++)

{

System.out.println("\n " + da[i]); }

}

public static void main(String args[]) {

array3 d = new array3(); d.disp();

} }

(15)

Explain Types of Operators Available in Java ?

 Operators are special symbols used in expressions.

 They include arithmetic operators, assignment operators, increment and decrement operators, logical operators, bitwise operators and comparison operators.

Arithmetic Operators

 Java has five basic arithmetic operators.

 Each of these operators takes two operands, one on either side of the operator. The list of arithmetic operators is given below:

Operator Meaning Example

+ Addition 8 + 10

- Subtraction 10 – 8

* Multiplication 20 * 84

/ Division 10 / 5

% Modulus 10 % 6

 The subtraction operator is also used to negate a single operand.

 Integer division results in an integer. Any remainder due to integer division is ignored. Modulus gives the remainder once the division has been completed. For integer types,

 the result is an int regardless of the type of the operands.  If any one or both the operands is of type long,

 then the result is also long. If one operand is an int and the other is float, then the result is a float.

Assignment Operators

 The assignment operators used in C and C + are also used in Java. A selection of assignment operators is given.

Expression Meaning X += y X = x + y X -= y X = x – y X *= y X = x * y X /= y X = x / y X=y X = y

Incrementing and Decrementing

 To increment or decrement a value by one, the ++ operator and -- operator are used respectively. The increment and the decrement operators can be prefixed or postfixed. The different increment and decrement operators can be used as given below:

 ++a (Pre – increment operator): Increment “a” by 1, then use the new value of “a” in the expression in which “a” resides.

 a++ (Post – increment operator): Use the current value of “a” in the expression in which “a” resides and then increment “a” by 1.

 --b (Pre – decrement operator): Decrement “b” by 1, then use the new value of “b” in the expression in which “b” resides.

(16)

 b--(Post decrement operator): Use the current value of “b” in the expression in which “b” resides and then increment “b” by 1.

Comparison Operators

 There are several expressions for testing equality and magnitude.  All these expressions return a boolean value.

 Table lists the comparison operators.

Operator Meaning Example

== Equal U == 45

!= Not equal U != 75

< Less than U < 85

> Greater than U > 68

<= Less than or equal to U<= 53

>= Greater than or equal to U >= 64

Logical Operators

 Logical operators available are AND, OR and NOT.

 The AND operator (& or &&) returns true only if both sides in an expression are true. If any one side fails, the operator returns false.

 For example, consider the following statement marks >= 40 && age >=65

 This condition is true if and only if both the simple conditions are true.  In the && operator, if the left side of the expression returns false,  the whole expression returns false and the right side is totally neglected.  The & operator evaluates both sides irrespective of outcome.

 The | or || is used for OR combination. This returns true if any of the expressions is true.

 Only if the all the conditions are false, the expression is false. Consider the following statement

semesterAverage >= 90 | | finalExam >= 90  the above condition is true if either of the two conditions is true.  The || evaluates the left expression first and if it returns true,  never evaluates the right side expression.

 A single | evaluates both the expressions regardless of the outcome.  The ! operator is used for NOT.

 The value of NOT is negation of the expression. 

(17)

Bitwise Operators

 The bitwise operators are inherited from C and C++.

 They are used to perform operations on individual bits in integers.  A list of the bitwise operators available is given in Table

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

<< Left Shift

>> Right Shift

>>>> Zero fill right shift

~ Bitwise Complement

<<= Left Shift Assignment

>>= Right Shift assignment

>>>= Zero fill right shift assignment

X &=y AND assignment

X |= y OR assignment

X ^= y XOR assignment

Conditional Operator (ternary operator)

 The conditional operator is also known as the ternary operator and is considered to be an alternative to the if…else construct.

 It returns a value and the syntax is: Syntax

<condition> ? <true statement> : <false statement>

 where, <condition> is the condition to be tested. If the condition returns true then the statement given in <true> will be executed.

(18)

CHAPTER 2

CLASS FUNDAS

WHAT CLASS / STATIC VARIABLE ?

 Class variables apply to a class as a whole.

 It is necessary to store the same information for every object.

 They are useful for keeping track of classwide information among a group of objects.

 All instances of the class have access to the same copy.

 The static keyword is used to declare a class static variable. Class MyPoint {

int x; int y;

Static int quadrant=1; // method 1

// method 2 }

In the above example x and y are instance variable whereas quadrant is a class / static variable.

public class MyPoint {

int x = 0; int y = 0;

void displayPoint() {

System.out.println("Printing the coordinates"); System.out.println(x + " " + y);

}

public static void main(String args[]) {

MyPoint obj; // declaration

obj = new MyPoint(); // allocation of memory to an object obj.displayPoint(); // calling a member function

} }

(19)

// Example of static variable . class Static1 { int a; int b; static int c; Static1() { a = 1; b = 2; } void display() { c++; System.out.println("\n\n a " + a + "\tb " + b + "\tc " + c); }

public static void main(String args[]) {

Static1 obj1 = new Static1(); Static1 obj2 = new Static1(); Static1 obj3 = new Static1(); obj1.display();

obj2.display(); obj3.display(); }

}

HOW TO DEFINE METHOD ?

Methods are defined as follows

 Return type

 Name of the method  A list of parameters  Body of the method. void displayPoint() {

// body of the method }

 In the above example return type is void.

 It means the method does not return any value.

(20)

 The parameters for this method are nil.

 If the return type is not void then the return keyword has to be used within the body of the method to return the value.

 The name of the method and the list of parameters are called as the signature of the method.

 Return type of the method is not part of the method‟s signature.

 A variable declared can be used only within the block it has been declared.

 It has a limited scope within which it can be used.

 If the variable is not a local variable, that is if it is not defined within the current method then java checks for the definition of that variable as an instance or class variable in the current class.

 If the definition is not found still then it is checked in each superclass in turn.

 Consider the case when same variable name is used for both local variable and instance variable/class variable.

 When the values are printed, the values of local variables are printed.

 The declaration of local variable hides the value of instance or class variables.

 However the values of instance or class variables can be accessed by using the keyword this along with the variable name.

 The example below shows the use of this keyword // An example of this. class This1 { int x = 10; int y = 20; void display() { int x = 5; int y = 6;

System.out.println("\n\n\n\t--Printing Local variables -- "); System.out.println("\n\t\t" + x + "\t" + y);

(21)

System.out.println("\n\n\n\t--Printing Instance variables -- "); System.out.println("\n\t\t" + this.x + "\t" + this.y);

}

public static void main(String args[]) {

This1 obj = new This1(); obj.display();

} }

 Parameter-list: It is a sequence of type & identifiers pairs separated by commas.

 Parameters are variables that receive the value of the argument passed to the method when it is called.

 If the method has no parameters, then the parameter list will be empty.

 Method that has a return type other than void, returns a value to the calling routine using the following form of the return statement;

return value;

3. what is constructors ? explain with an example ? [

Nov / Dec – 2008] , [March/April -2009]

 Every time when we create an object, we have to initialize all the variables of a class.

 Java allows objects to initialize themselves when they are created.

 This automatic initialization is performed with the use of constructor.

 A constructor allows objects to initialize themselves as soon as they are created.

 A constructor is automatically called when an object is created. It has the same name as the class in which it resides and is syntactically similar to a method.

 Constructors do not have return type not even void. The general form of declaring a constructor is:

Constructor_name([arguments]) {

// body }

(22)

1. Non-Parameterized 2. Parameterized

Non-Parameterized Constructor // Non - parameterised constructor class Point1 { int x; int y; Point1() { x = 10; y = 20; } void display() {

System.out.println("\n\n\t---Printing the coordinates---"); System.out.println("\t\t\t" + x + " " + y);

}

public static void main(String args[]) {

Point1 p1 = new Point1(); p1.display(); } } Parameterized Constructor // parameterised constructor class Point2 { int x; int y; Point2(int a, int b) { x = a; y = b; } void display() {

System.out.println("\n\n\t---Printing the coordinates---"); System.out.println("\t\t\t" + x + " " + y);

(23)

public static void main(String args[]) {

Point2 p1 = new Point2(10,20); p1.display();

} }

4. explain Method Overloading ? with Example ? [

Nov / Dec – 2008] , [March/April -2009] , [Oct / Nov – 2009]

 A class can contain any number of methods. Methods can be with parameter and without parameter.

 The parameter in a method are called type signature.

 It is possible in java to define two or more methods within the same class that share the same name,

 but with different parameter declarations (type signatures).

 When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.

 Overloading methods demonstrate the concept of polymorphism.

 When an overloaded method is invoked, java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to call.

 Thus, overloaded methods must differ in the type and/or number of their parameters.

 Overloaded methods may have different return types.

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

// An example of Method Overloading class MethodOver { int n1; int n2; MethodOver() { n1 = 10; n2 = 20; }

(24)

void square() { System.out.println("\n\n\tThe Square is " + n1 * n2); } void square(int p1) { n1 = p1; System.out.println("\n\n\tThe Square is " + n1 * n2); }

void square(int p1, int p2) {

n1 = p1; n2 = p2;

System.out.println("\n\n\tThe Square is " + n1 * n2); }

public static void main(String args[]) {

MethodOver obj1 = new MethodOver(); obj1.square();

obj1.square(4); obj1.square(7,8); }

}

5. Exaplin Constructor Overloading ? With Example ?

[

Nov / Dec – 2008]

 Along with method overloading,

 we can also overload constructors. Constructors having the same name with different parameter list is called constructor overloading.

// constructor with object as parameter class Point { int x; int y; Point(int a, int b) { x = a; y = b; } } class Circle { int originX;

(25)

int radius; //Default Constructor Circle() { originX = 5; originY = 5; radius = 3; }

// Constructor initializing the coordinates of origin and the radius. Circle(int x1, int y1, int r)

{ originX = x1; originY = y1; radius = r; } Circle(Point p, int r) { originX = p.x; originY = p.y; radius = r; } void display() {

System.out.println("\n\t--Center at " + originX + " and " + originY); System.out.println("Radius = " + radius);

}

public static void main(String args[]) {

Circle c1 = new Circle();

Circle c2 = new Circle(10,20,5);

Circle c3 = new Circle(new Point(15,25),10); c1.display();

c2.display(); c3.display();

(26)

} }

6. How to Pass Objects as a Parameter to Method ?

 We have seen that methods can take parameters as input and process them.

 It is also common to pass objects as a parameter to methods. // An example of Passing Object as parameter to method

class PassObj { int n1; int n2; // constructor PassObj() { n1 = 0; n2 = 0; } PassObj(int p1, int p2) { n1 = p1; n2 = p2; } void multiply(PassObj p1) { int temp; temp = p1.n1 * p1.n2; System.out.println("\n\n\tMultiplication is " + temp); }

public static void main(String args[]) {

PassObj obj1 = new PassObj(5,6); PassObj obj2 = new PassObj(); obj2.multiply(obj1);

} }

7. Explain Method overloading with object as a parameter ?

// An example of Method overloading with object as a parameter class MetObjOv

{

(27)

// constructor MetObjOv() { n1 = 0; n2 = 0; } MetObjOv(int x, int y) { n1 = x; n2 = y; } void multiply(MetObjOv p1) { n1 = p1.n1; n2 = p1.n2;

System.out.println("\n\n\tThere is nothing to multiply "); System.out.println("\tn1 = "+n1+"\tn2 = " +n2);

}

void multiply(MetObjOv p1, MetObjOv p2) {

n1 = p1.n1 * p2.n1; n2 = p1.n2 * p2.n2;

System.out.println("\n\n\tMultiplication of two objects "); System.out.println("\tn1 = " + n1 + "\tn2 = " + n2 ); }

public static void main(String args[]) {

MetObjOv obj1 = new MetObjOv(5,6); MetObjOv obj2 = new MetObjOv(6,5); MetObjOv obj3 = new MetObjOv(); obj3.multiply(obj1);

obj3.multiply(obj1, obj2); }

}

8. How to Return an Object ? Explain with an Example ?

 A method can return any type of data, including class type (object) that you create.

// An example of returning an object class RetObj

{

(28)

int n2; // constructor RetObj() { n1 = 0; n2 = 0; } RetObj(int x, int y) { n1 = x; n2 = y; }

RetObj multiply(RetObj p1, RetObj p2) { n1 = p1.n1 * p2.n1; n2 = p1.n2 * p2.n2; return (this); } void display() {

System.out.println("\n\n\tAn Example of returning an Object "); System.out.println("\tn1 = "+n1+"\tn2 = " +n2);

}

public static void main(String args[]) {

RetObj obj1 = new RetObj(5,6); RetObj obj2 = new RetObj(6,5); RetObj obj3 = new RetObj(); obj3 = obj3.multiply(obj1, obj2); obj3.display();

} }

11. How to Pass Arguments in Java ? Call by value and Reference ?

 Computer language can pass an argument to a subroutine in following two ways:

[1] call-by-value [2] call-by-reference

[1] Call-by-Value

 This method copies the value of an argument into the formal parameter of the subroutine.

(29)

 Therefore, changes made to the parameter of the subroutine have no effect on the argument.

 In java, when we pass a primitive type to a method, it is passed by value.

 Thus, what occurs to the parameter that receives the argument has no effect outside the method.

/* An example of call by value */ class CallVal { int a, b; CallVal() { a = b = 0; } CallVal(int x, int y) { a = x; b = y; }

void Interchange(int Temp) { Temp = 100; System.out.println("\n\n\tCall by Value "); System.out.println("\n\n\tTemp = " + Temp); } void display() { System.out.println("\n\n\ta = " + a + "\tb = " + b); }

public static void main(String args[]) {

CallVal obj1 = new CallVal(10,20); int var = 11;

System.out.println("\n\n\tThe value of var is " + var); obj1.Interchange(var);

System.out.println("\n\n\tThe value of var is " + var); }

}

[2] Call-by-Reference

 A reference to an argument (not value of argument) is passed to the parameter.

 Inside the subroutine, this reference is used to access the actual argument specified in the call.

(30)

 This means that changes made to the parameters will affect the argument used to call the subroutine.

 When we pass an object to a method, the situation changes, because objects are passed by call-by-reference.

 When we create a variable of a class type, we are only creating a reference to an object. Thus,

 when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.

 This effectively means that objects are passed to method do affect the object used as an argument.

/* An example of call by Reference*/ class CallRef { int a, b; CallRef() { a = b = 0; } CallRef(int x, int y) { a = x; b = y; }

void Interchange(CallRef Temp) { Temp.a = 100; Temp.b = 200; System.out.println("\n\n\tCall by Reference "); System.out.println("\n\n\tTemp.a = " + Temp.a); System.out.println("\n\n\tTemp.b = " + Temp.b); } void display() { System.out.println("\n\n\ta = " + a); System.out.println("\n\n\tb = " + b); }

public static void main(String args[]) {

CallRef obj1 = new CallRef(10,20); obj1.display();

obj1.Interchange(obj1); obj1.display();

(31)

14. Exaplin Access Control ? [

Nov / Dec – 2008] , [March/April -2009] ,

[Oct / Nov – 2009]

 One can control what parts of a program can access the member of a class. By controlling access, one can prevent misuse.

 For Example, allowing access to data only through a well-defined set of methods, one can prevent misuse of that data. Thus,

 when correctly implemented, a class creates “black box”.

 How a member can be accessed is determined by the access specifier that modifies its declaration.

 Java provides a set to access specifiers. Some aspects of access control are related to inheritance or packages.

 Java‟s access specifiers are:

public:

o When a member of a class is specified by the public specifier, then that member can be accessed by any other code.

o The public modifier makes a method or variable completely available to all classes.

o Also when the class is defined as public, it can be accessed by any other class.

private:

o To hide a method or variable from other classes, private modifier is used.

o A private variable can be used by methods in it‟s own class but not by objects of any other class.

o Neither private variables nor private methods are inherited by subclass.

o The only place these variables and methods can be seen is from within their own class.

protected:

o protected applies only when inheritance is involved.

o If you want to allow an element to be seen outside your current package, but only to classes that are inherited from your class directly, then declare that element as protected.

default:

o We have seen that when no access control modifier is specified, it is called as default access.

(32)

o Any variable declared without a modifier can be read or changed by any other class in the same package.

o Any method declared the same way can be called by any other class in the same package.

o When a member does not have an explicit access specification, o it is visible to subclasses as well as to other classes in the same

package.

 The following table summarizes the levels of access control.

Access Public Protected Default Private

From the same class

Yes Yes Yes Yes

From any class in the same package

Yes Yes Yes No

From any class outside the package Yes No No No From a sub - class in the same package

Yes Yes Yes No

From a sub - class outside the same package

Yes Yes Yes No

Exaplin static keyword ? [

Nov / Dec – 2008]

 A class member must be accessed with the use of an object of its class but sometimes we want to define a class member that will be used independently without creating any object of that class.

 It is possible in java to create a member that can be used by itself, without reference to a specific instance.

 To create such a member, precede its declaration with the keyword static.

 When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

 one can declare both methods and variables to be static.

 The most common example of a static member is main().

 Main() is declared as static because it must be called before any object exist.

 Instance variables declared as static are actually, global variables.

 When objects of its class are declared, no copy of a static variable is made.

 Instead, all instances of the class share the same static variable. Method declared as static have several restrictions:

(33)

1. Can call only other static methods. 2. Only access static data.

3. Can not refer to this or super in any way.

 One can also declare a static block which gets executed exactly once, when the class is first loaded.

/* An example of Static Variable */ class StaticDemo

{

static int x = 3; static int y;

static void display(int z) { System.out.println("\n\n\tz = " + z); System.out.println("\n\n\tx = " + x); System.out.println("\n\n\ty = " + y); } static {

System.out.println("\n\n\tStatic block initialized"); y = x*4;

}

public static void main(String args[]) {

display(42); }

}

18. What is Nested / Inner Classes ?

 It is possible to define a class within another class; such classes are known as nested classes.

 The scope of a nested class is bounded by the scope of its enclosing class.

 That means, if class B is defined within class A, then B is known to A, but not outside A.

 If A is nesting class B, then A has access to all the members of B, including private members. But the B does not have access to the members of nested class.

There are two types of nested classes: 1. Static

(34)

2. Non – Static Static nested class

 A static nested class is one which has the static modifier, as it is static it must access the member of its enclosing class through an object.

 That means it cannot refer to member of its enclosing class directly. Non – Static nested class

 Non – Static nested class is known as inner class.

 It has access to all of its variables and methods of its outer class and can refer to them directly.

 An inner class is fully within the scope of its enclosing class. /* An example of Inner class */

class Inner1 {

class Contents {

private int i = 16; public int value() { return i; } } class Destination {

private String label;

Destination(String whereTo) {

label = whereTo; }

}

public void ship(String dest) {

Contents c = new Contents();

Destination d = new Destination(dest);

System.out.println("\n\n\tShipped " + c.value() + " item(s) to " + dest);

}

public static void main(String args[]) {

Inner1 p = new Inner1(); p.ship("Congo");

(35)

}

CHAPTER 3

PACKAGES

1.

Explain

VECTOR CLASS with example ? [March/April -2009], [Oct / Nov

– 2009]

 The Vector class is one of the most important in all of the Java class libraries. We cannot expand the size of a static array.

 We may think of a vector as a dynamic array that automatically expands as more elements are added to it.

 All vectors are created with some initial capacity.

 When space is needed to accommodate more elements, the capacity is automatically increased.

 That is why vectors are commonly used in java programming. This class provides the following constructors:

Vector() Vector(int n)

Vector(int n, int delta)

 The first form creates a vector with an initial capacity of ten elements.  The second form creates a vector with an initial capacity of n elements.  The third form creates a vector with an initial capacity of n elements

that increases by delta elements each time it needs to expand.

Example 1

import java.util.*; class VectorDemo {

public static void main(String args[]) {

int i;

Vector v = new Vector();

v.addElement(new Integer(10)); v.addElement(new Float(5.5f)); v.addElement(new String("Hi")); v.addElement(new Long(2500)); v.addElement(new Double(23.25));

(36)

System.out.println(v);

String s = new String("Bhagirath"); v.insertElementAt(s,1); System.out.println(v); v.removeElementAt(2); System.out.println(v); for(i=0;i<5;i++) { System.out.println(v.elementAt(i)); } } }

2.

Explain

Random class with an example ? [March/April -2009]

 The Random class allows you to generate random double, float, int, or long numbers.

 This can be very helpful if you are building a simulation of a real-world system.

 This class provides the following constructors. Random()

Random(long start)

 Here, start is a value to initialize the random number generator.

Method Description

Double nextDouble() Returns a random double value.

Float nextFloat() Returns a random float value.

Double nextGaussian() Returns a random double value. Numbers obtained from repeated calls to this method have a Gaussian distribution with a mean of 0 and a standard deviation of 1.

Int nextInt() Returns a random int value.

Long nextLong() Returns a random long value.

Example 2

import java.util.*; class RandomDemo {

public static void main(String args[]) {

Random ran = new Random(); for(int i = 0; i<5;i++)

{

(37)

} }

}

3.

Explain

Date class an example ? [March/April -2009]

 The Date classes encapsulate information about a specific date and time.

 It provides the following constructors. Date()

Date(long msec)

 Here, the first form returns an object that represent the current date and time.

 The second form returns an object that represents the date and time msec in milliseconds after the time.

 The time is defined as midnight on January 1,1970 GMT (Greenwich Mean Time).

Method Description

Boolean after(Date d) Returns true if d is after the current date. Otherwise, returns false.

Boolean before(Date d) Returns true if d is before the current date. Otherwise, returns false.

Boolean equals(Date d) Returns true if d has the same value as the current date. Otherwise, returns false.

Long getTime() Returns the number of milliseconds since the epoch.

Void setTime

(long msec) Sets the date and time of the current object to represent msec milliseconds since the epoch.

String toString() Returns the string equivalent of the date.

Example

import java.util.*; class DateDemo {

public static void main(String args[]) {

Date dt = new Date(); System.out.println(dt); Date epoch = new Date(0); System.out.println(epoch); }

(38)

}

Example

import java.util.Date; public class date2 {

public static void main(String[] args) {

Date d1 = new Date(); try { Thread.sleep(1000); } catch(Exception e){}

Date d2 = new Date();

System.out.println("First Date : " + d1); System.out.println("Second Date : " + d2);

System.out.println("Is second date after first ? : " + d2.after(d1)); }

}

Example

import java.util.*; public class date3{

public static void main(String args[]){ Date date = new Date();

System.out.println("Date is : " + date);

System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : " + date.getTime());

Date epoch = new Date(0); date.setTime(10000);

System.out.println("Time after 10 second " + epoch); System.out.println("Time after 10 second " + date);

(39)

String st = date.toString(); System.out.println(st); }

}

4.

Explain

Calendar and Gregorian class with an example ? [March/April

-2009]

 The Calendar class allows you to interpret date and time information.  This class defines several integer constants that are used when you get

or set components of the calendar. These are listed here:

AM AM_PM APRIL

AUGUST DATE DAY_OF_MONTH

DAY_OF_WEEK DAY_OF_WEEK_IN_MONTH DAY_OF_YEAR

DECEMBER DST_OFFSET ERA

FEBRUARY FIELD_COUNT FRIDAY

HOUR HOUR_OF_DAY JANUARY

JULY JUNE MARCH

MAY MILLISECOND MINUTE

MONDAY MONTH NOVEMBER

OCTOBER PM SATURADAY

SECOND SEPTEMBER SUNDAY

THURSDAY TUESDAY UNDERIMBER

WEDNESDAY WEEK_OF_MONTH WEEK_OF_YEAR

YEAR ZONE_OFFSET

 The Calendar class does not have public constructors. Instead, you may use the static getInstance() method to obtain a calendar initialized to the current date and time.

One of its forms is shown here: Calendar getInstance()

Example

import java.util.Calendar; public class Cal1 {

public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

System.out.println("DATE is : " + cal.get(cal.DATE)); System.out.println("YEAR is : " + cal.get(cal.YEAR)); System.out.println("MONTH is : " + cal.get(cal.MONTH));

(40)

System.out.println("DAY OF WEEK is : " + cal.get(cal.DAY_OF_WEEK)); System.out.println("WEEK OF MONTH is : " + cal.get(cal.WEEK_OF_MONTH));

System.out.println("DAY OF YEAR is : " + cal.get(cal.DAY_OF_YEAR)); System.out.println("DAY OF MONTH is : " + cal.get(cal.DAY_OF_MONTH));

System.out.println("WEEK OF YEAR is : " + cal.get(cal.WEEK_OF_YEAR)); System.out.println("HOUR is : " + cal.get(cal.HOUR));

System.out.println("MINUTE is : " + cal.get(cal.MINUTE)); System.out.println("SECOND is : " + cal.get(cal.SECOND));

System.out.println("DAY OF WEEK IN MONTH is : " + cal.get(cal.DAY_OF_WEEK_IN_MONTH));

System.out.println("Era is : " + cal.get(cal.ERA));

System.out.println("HOUR OF DAY is : " + cal.get(cal.HOUR_OF_DAY)); System.out.println("MILLISECOND : " + cal.get(cal.MILLISECOND)); System.out.println("AM_PM : " + cal.get(cal.AM_PM));// Returns 0 if AM and 1 if PM

} }

 The GregorianCalendar class is a subclass of Calendar.

 It provides the logic to manage date and time information according to the rules of the Gregorian calendar.

 This class provides following constructors: GregorianCalendar()

GregorianCalendar(int year, int month, int date)

GregorianCalendar(int year, int month, int date, int hour, int minute, int sec)

GregorianCalendar(int year, int month, int date, int hour, int minute)  The first form creates an object initialized with the current date and

time.

 The other forms allow you to specify how various date and time components are initialized.

 The class provides all of the method defined by Calendar and also adds the isLeapYear() method shown here:

Boolean isLeapYear()

 This method returns true if the current year is a leap year. Otherwise, it returns false.

Example

(41)

public class gcal1 {

public static void main(String[] args) {

GregorianCalendar c1 = new GregorianCalendar() ;

System.out.println("DATE is : " + c1.get(c1.DATE)); System.out.println("YEAR is : " + c1.get(c1.YEAR)); System.out.println("MONTH is : " + c1.get(c1.MONTH));

System.out.println("DAY OF WEEK is : " + c1.get(c1.DAY_OF_WEEK)); System.out.println("WEEK OF MONTH is : " + c1.get(c1.WEEK_OF_MONTH));

System.out.println("DAY OF YEAR is : " + c1.get(c1.DAY_OF_YEAR)); System.out.println("DAY OF MONTH is : " + c1.get(c1.DAY_OF_MONTH));

System.out.println("WEEK OF YEAR is : " + c1.get(c1.WEEK_OF_YEAR)); System.out.println("HOUR is : " + c1.get(c1.HOUR));

System.out.println("MINUTE is : " + c1.get(c1.MINUTE)); System.out.println("SECOND is : " + c1.get(c1.SECOND));

System.out.println("DAY OF WEEK IN MONTH is : " + c1.get(c1.DAY_OF_WEEK_IN_MONTH));

System.out.println("Era is : " + c1.get(c1.ERA));

System.out.println("HOUR OF DAY is : " + c1.get(c1.HOUR_OF_DAY)); System.out.println("MILLISECOND : " + c1.get(c1.MILLISECOND));

System.out.println("AM_PM : " + c1.get(c1.AM_PM));// Returns 0 if AM and 1 if PM */

} }

5.

Explain

Math Class with an example ? [March/April -2009] , [Oct / Nov – 2009]

 For scientific and engineering calculations, a variety of mathematical functions are required.

 Java provides these functions in the Math class available in java.lang package.

 The methods defined in Math class are given following:

Method Description

Double sin(double x) Returns the sine value of angle x in radians.

Double cos(double x) Returns the cosine value of the angle x in radians

Double tan(double x) Returns the tangent value of the angle x in radians

(42)

arcsin of x

Double acos(double x) Returns angle value in radians for arcos of x

Double atan(double x) Returns angle value in radians for arctangent of x

Double exp(double x) Returns exponential value of x Double log(double x) Returns the natural logarithm of x Double pow(double x, double y) Returns x to the power of y

Double sqrt(double x) Returns the square root of x

Int abs(double n) Returns absolute value of n

Double ceil(double x) Returns the smallest wholoe number greater than or equal to x

Double floor(double x) Returns the largest whole number less than or equal to x

Int max(itn n, int m) Returns the maximum of n and m Int min(int n, int m) Returns the minimum of n and m Double rint(double x) Returns the rounded whole number

of x

Int round(float x) Returns the rounded int value of x Long round(double x) Returns the rounded int value of x Double random() Returns a random value between 0

and 1.0

Double toRandians(double angle) Converts the angle in degrees to radians

Double toDegrees(double angle) Converts the angle in radians to degrees

6.

Explain

Wrapper Class with an example ?

[

Nov / Dec – 2008] , [March/April -2009] , [Oct / Nov – 2009]

 Java uses primitive types, such as int, char, double to hold the basic data types supported by the language.

 Sometimes it is required to create an object representation of these primitive types.

 These are collection classes that deal only with such objects. One needs to wrap the primitive type in a class.

 To satisfy this need, java provides classes that correspond to each of the primitive types. Basically, these classes encapsulate, or wrap, the primitive types within a class.

 Thus, they are commonly referred to as type wrapper. Type wrapper are classes that encapsulate a primitive type within an object.

 The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float.

(43)

 These classes offer a wide array of methods that allow to fully integrate the primitive types into Java‟s object hierarchy.

Byte

 The Byte class encapsulates a byte value. It defines the constants MAX_VALUE and MIN_VALUE and provides these constructors:

Byte(byte b) Byte(String str)

Here, b is a byte value and str is the string equivalent of a byte value.

Example

import java.util.*; class Byte1

{

public static void main(String args[]) {

Byte b1 = new Byte((byte)120); for(int i = 125; i<=135; i++) {

Byte b2 = new Byte((byte)i); System.out.println("b2 = " + b2); }

System.out.println("b1 Object = " + b1);

System.out.println("Minimum Value of Byte = " + Byte.MIN_VALUE); System.out.println("Maximum Value of Byte = " + Byte.MAX_VALUE); System.out.println("b1* 2 = " + b1*2);

System.out.println("b1* 2 = " + b1.byteValue()*2); Byte b3 = new Byte("120");

System.out.println("b3 Object = " + b3);

System.out.println("(b1==b3)? " + b1.equals(b3));

System.out.println("(b1.compareTo(b3)? " + b1.compareTo(b3)); /*Returns 0 if equal. Returns -1 if b1 is less than b3 and 1 if b1 is greater than 1*/

} }

Short

 The Short class encapsulates a short value. It defines the constants MAX_VALUE and MIN_VALUE and provides the following constructors:

Short(short s) Short(String str) Example import java.util.*; class Short1 {

(44)

{

Short s1 = new Short((short)2345); for(int i = 32765; i<=32775; i++) {

Short s2 = new Short((short)i); System.out.println("s2 = " + s2); }

System.out.println("s1 Object = " + s1);

System.out.println("Minimum Value of Short = " + Short.MIN_VALUE); System.out.println("Maximum Value of Short = " + Short.MAX_VALUE); System.out.println("s1* 2 = " + s1.shortValue()*2);

Short s3 = new Short("2345");

System.out.println("s3 Object = " + s3); System.out.println("(s1==s3)? " + s1.equals(s3)); Short s4 = Short.valueOf("10", 16); System.out.println("s4 Object = " + s4); } }  Integer

 The Integer class encapsulates an integer value. This class provides following constructors:

Integer(int i) Integer(String str)

Here, i is a simple int value and str is a String object.

Example

import java.util.*; class int1

{

public static void main(String args[]) {

Integer i1 = new Integer(12); System.out.println("I1 = " + i1);

System.out.println("Binary Equivalent = " + Integer.toBinaryString(i1)); System.out.println("Hexadecimal Equivalent = " + Integer.toHexString(i1));

System.out.println("Minimum Value of Integer = " + Integer.MIN_VALUE);

System.out.println("Maximum Value of Integer = " + Integer.MAX_VALUE);

System.out.println("Byte Value of Integer = " + i1.byteValue()); System.out.println("Double Value of Integer = " + i1.doubleValue()); Integer i2 = new Integer(12);

System.out.println("i1==i2 " + i1.equals(i2));

System.out.println("i1.compareTo(i2) = " + i2.compareTo(i1));

(45)

Integer i3 = Integer.valueOf("11", 16); System.out.println("i3 = " + i3); } }  Long

 The Long class encapsulates a long value. It defines the constants MAX_VALUE and MIN_VALUE and provides the following constructors: Long(long l) Long(String str) Example import java.util.*; class longdemo {

public static void main(String args[]) {

Long L1 = new Long(68764); Long L2 = new Long("686748");

System.out.println("Object L1 = " + L1); System.out.println("Object L2 = " + L2);

System.out.println("Minimum Value of Long = " + Long.MIN_VALUE);

System.out.println("Maximum Value of Long = " + Long.MAX_VALUE); System.out.println("L1 * 2 = " + L1 * 2); System.out.println("L1.longValue() * 2 = " + L1.longValue() * 2); System.out.println("L1.compareTo(l2) = " + L1.compareTo(L2)); System.out.println("L1==L2 ? = " + L1.equals(L2)); Long L3 = Long.valueOf("10", 16); System.out.println("Object L3 = " + L3);

System.out.println("Byte value of Long = " + L1.byteValue()); System.out.println("int value of Long = " + L1.intValue());

System.out.println("Double value of Long = " + L1.doubleValue());

int i = 12;

System.out.println("Binary equivalent of decimal " + i + "=" + Long.toBinaryString(i));

System.out.println("Hexadecimal equivalent of decimal " + i + "=" + Long.toHexString(i));

} }

Double

(46)

 The largest and smallest values are saved in MAX_VALUE and MIN_VALUE.

 The constant NaN (Not a Number) indicates that a value is not a number.  If you divide a double number by zero, the result is NaN. This class

defines these constructors: Double(double d) Double(String str)

 Here, d is a double value to be encapsulated in a Double object. In the last form, str is the string representation of a double value.

Example

import java.util.*; class double1 {

public static void main(String args[]) {

Double d1 = new Double(687642365.4563); Double d2 = new Double("686748");

System.out.println("Object d1 = " + d1); System.out.println("Object d2 = " + d2);

System.out.println("Minimum Value of Double = " + Double.MIN_VALUE);

System.out.println("Maximum Value of Double = " + Double.MAX_VALUE);

System.out.println("Byte value of Double = " + d1.byteValue()); System.out.println("int value of Double = " + d1.intValue()); System.out.println("Float value of Double = " + d1.floatValue()); Double d3 = Double.parseDoduble("765.89");

System.out.println("Double value from the string \"765.89\"="+d3);

} }

Float

 The float class encapsulates a float value. It defines several constants:  the largest and smallest values are stored in MAX_VALUE and

MIN_VALUE.

 The constant NaN indicates that a value is not a number. If you divide a floating – point number by zero, the result is NaN.

 This class defines these constructors: Float(float f)

Float(double d) Float(String str)

(47)

 Here, f and d are float and double types to be encapsulated in a Float object.

 str is the string representation of a float value.

Example

import java.util.*; class Float1 {

public static void main(String args[]) {

Float f1 = new Float(123.5626); Float f2 = new Float(854.32f); Float i = new Float(10);

System.out.println("Object f1 = " + f1); System.out.println("Object f2 = " + f2);

System.out.println("Minimum Value of Float = " + Float.MIN_VALUE);

System.out.println("Maximum Value of Float = " + Float.MAX_VALUE);

System.out.println("Byte value of Float = " + f1.byteValue()); System.out.println("Short value of Float = " + f1.shortValue()); System.out.println("Integer value of Float = " + f1.intValue()); System.out.println("Double value of Float = " + f1.doubleValue());

System.out.println("(f1==f2) ?= " + f1.equals(f2));

System.out.println("f1.compareTo(f2) = " + f1.compareTo(f2)); System.out.println("f1 is not a number = " + i.isNaN());

} }

Character

 The Character class encapsulates a char value. This class provides the following constructor.

Character(char ch)

 Here, c is a char value. charValue() method returns the char value that is encapsulated by a Character object and has the following form: char charValue()

Example

References

Related documents

The remaining constructs were identified as follows: Children’s Development (Understanding of the development of children’s concepts, abilities, skills, and attitudes); Planning

Hence, in practice, the usual approach is to determine the VTTS of the project under evaluation according to recommended values at a national level (see for example UNITE

The project was announced on Google by Project Glass lead Babak Parviz, an electrical engineer who has also worked on putting displays into contact lenses; Steve Lee, a

PF_RING Monitoring Application Monitoring Application Monitoring Application Ethernet nCap Legacy Straight Capture Userland Kernel.. nCap Features Packet Capture Acceleration Wire

To refute intelligent design, it is enough to display specific, fully articulated Darwinian pathways for the complex systems that, according to intelligent design, lie beyond

This tremendous growth in the e-commerce industry, will certainly give global merchants with an on-line presence the opportunity to strengthen international sales

This article charts the writing process for the three editions of the Australian Media Studies textbook Media: new ways and meanings, and places the book