• Nenhum resultado encontrado

java material msc

N/A
N/A
Protected

Academic year: 2021

Share "java material msc"

Copied!
56
0
0

Texto

(1)

UNIT – I: JAVA BASICS

Java Buzzwords

Sun micro system officially describes Java with following features. 1. Compiled and Interpreted:

 Java compiled both the compilation and interpreter, thus taking Java a two stage system.  At first Java compiler translates source code into byte code instructions. In the second

stage Java interpreter generates machine code, that can be directly executed by the machine that the running Java of the program.

2. Platform independent and portable:

 Java programs can be easily moved from one computer system to another, any where and any time. Changes and upgrades in operating systems. Processors and system resources will not force any changes in Java programs.

 On internet Java programming language interconnects different kinds of system world wide.

3. Object Oriented:

 Java is true object oriented language almost everything in Java is an object.  Java comes with an extensive set of classes, arranged in packages.

4. Robust and Secure:

 Java is a Robust language and provides many safe gods to ensure reliable code, it has strict compile time and run time checking for data types.

 Java is designed as a language to relieve the all virtually memory management problems. Java also incorporates the concept of execution handling.

 Security problems an important issue for a language that is used for programming on internet Java systems not only verify all memory access and also ensure that no verses communicated with Applet.

5. Distributed:

 Java is designed as a distributed language for creating applications on networks, it has the ability to share both data and programs.

 Java applications can open and access objects on internet as easily as they can do in a local system.

 Java enables multiple programs at multiple remote locations to collaborate and work together on a single project.

6. Simple, small and familiar:

 Java is a small and simple language. Many features C and C++ such as pointers, preprocessors, header files, goto statement, operator overloading and multiple inheritance are not part of Java.

 Java uses many constructs of C and C++, so Java code “looks like a C++” code. In fact Java is a simplified version of C++.

7. Multithreaded and Interactive:

 Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded programs. This means we need not wait for the applications to finish one task before beginning another.

 For example, we can listen an audio click while scrolling page and at the same time download an Applet from a remote control. This feature improves the interactive performance of graphical applications.

8. High performance:

(2)

 According to sun, Java speed is comparable to the native C and C++.  Java architecture is also designed to reduce over heads during run time.

9. Dynamic and Extensible:

 Java is capable of dynamically linking in new class library, methods & objects.

 Java programs support functions written other language such as C and C++, these functions are known as native methods. Native methods are linked dynamically at runtime.

Data Types

In java there are two types of data types. Such as primitive and non-primitive.

Integer:

The integer type numbers contains without decimal part either positive or negative. Java supports 4 types of integers. They are byte, short, int and long.

Type Memory size Min Max

Byte 1 byte -128 127

Short 2 bytes -32768 32767

Int 4 bytes -2147483648 2147483647

Long 8 bytes -9223372036854775807 9223372036854775808 Float:

The floating point type numbers contains decimal part either positive or negative. There are 2 types of floating points.

 The float type values are single precision numbers.  The double type values are double precision numbers.

The single precision mode is used by appending ‘f’ or ‘F’ to the numbers.

Type Memory size Min Max

Float 4 bytes 3.4e-38 3.4e+38

Double 8 bytes 1.7e-308 1.7e+308

Character:

Java provides a character data type called char to store a character constant. The character type assumes a size of two bytes and holds only a single character.

Boolean:

The Boolean type is used to test a particular condition during the execution of a program. There are only 2 values that a Boolean type can take, they are true and false. Boolean type is denoted by boolean and uses only one bit of storage.

Data Types Primitive (Built-in) Non-primitive (Derived) Non-Numeric Numeric float

integer character boolean Interface

Arrays Class

(3)

Variables

A variable is an identifier that denotes a storage location to store a data value. A variable may take different values at different times during execution of the program. For naming a variable we have follow following rules.

 The variable must begin with an alphabet.  Upper and lower case letters are different.  It should not be a keyword.

 White space is not allowed.

 Variables names can be of any length. Scope of variables

Java variables are classified into three kinds.  Instance variables

 Class variables  Local variables

 Instance and class variables are declared inside a class. Instance variables are created when the objects are instantiated and therefore they are associated with the objects.

 Class variables are global to a class belong to the entire set of objects that class creates.

 Variables declared and used inside methods are called local variables they are not available for use outside the method definition.

 Local variables can also be declared inside program blocks between opening and closing brace.  The area of the program where the variable is accessible is called its scope.

We cannot declare a variable we have the same name as one in other block.

In the above figure the variable x in block-1 is available all the three blocks. But variable m in block-2 and variable n in block-3 only in that blocks.

Giving values to variables

Values can be given to a variable in two ways.  By using an assignment statement.  By using an read statement

Assignment Statement:

A simple method of giving values to variables is through the assignment statement. Syn: variablename=value; { int x=10; ……….. { int m=5; } { int n=5; }

(4)

Eg: a=10;

We can also assign a value to variable at the time of declaration. Syn: datatype variablename=value;

Eg: int a=10; Read Statement:

 We may also give values to a variable through the keyword using readLine() method.

 The redLine() method, which is an object of BufferedReader class. It is used to read input from the keyboard as a string which is converted to the corresponding data type using the wrapper classes. Operators and Expressions

Java operators can be classified into 8 types. They are 1. Arithmetic Operators

2. Relational Operators 3. Logical Operators 4. Assignment Operators

5. Increment Operators and Decrement Operators 6. Conditional Operators

7. Bit wise Operators 8. Special Operators Arithmetic Operators:

Arithmetic operators are used to construct mathematical expressions. Operator Meaning + Addition - Subtraction * Multiplication / Division % Reminder

The expressions such as a+b, a-b+c a*b*c are called Arithmetic expressions.

a) Integer Arithmetic : When both the operands are integers, then the operation is called integer arithmetic.

Eg: If a and b are integers a=14 and b=4 then a+b=18

a-b= 10 a*b= 56 a/b= 3 a%b= 2

b) Real Arithmetic : When both the operands are real, then the operation is called real arithmetic. Eg: a=5.0 and b=2.0 then a/b=5.0/2.0=2.5

c) Mixed-mode Arithmetic : When one of the operand is integer and other is real, then the operation is called mixed-mode arithmetic.

Eg: a=5 and b=2.0 then a/b=5/2.0=2.5 (or) a/b=5.0/2=2.5 Relational Operators:

Comparisons can be done with the help of relational operators. The expression such as a<b, b>c, c==d is called a relational expressions. The value of relational expressions is either true or false.

Operator Meaning

< Less than

<= Less than or equal to > Greater than

(5)

>= Greater than

== Equal to

!= Not equal to

The expressions such as a<b, a>b and a==b are called relational expressions.

A simple relational expression contains only one relational operator and is the following ae-1 relational operator ae-2

Here ae-1 and ae-2 are arithmetic expressions, which may be constants, variables and combination of them.

Relational expressions are used in loop control statements, such as if, while and do…while. Logical Operators:

Java has following three logical operators. Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

The logical operators are used to form compound conditions by combining two or more relational expressions, such expressions are called as a logical expression.

(a,b)&&(b>c), (a==b)||(b==c)

OP-1 OP-2 OP-1 && OP-2 OP-1 || OP-2

T T T T

T F F T

F T F T

F F F F

Assignment Operator:

Assignment operator ‘=’ is used to assign a value of an expression to a variable. Java has a set of ‘shorthand’ assignment operators which are used in the form.

Syn: v op=exp;

Where ‘v’ is a variable, ‘op’ is a operator and ‘exp’ is an expression. Statement with Statement with

assignment operator shorhand

a=a+2 a+=2

a=a-3 a-=3

a=a*(n+1) a*=(n+1)

a=a/(n+1) a/=(n+1)

a=a%b a%=b

Increment and Decrement Operators:

The increment operator ‘++’ adds 1 to the operand and the decrement operator ‘--‘ subtracts 1 from the operand. Both the unary operators are used to the following form.

m++, post increment ++m, pre increment m--, post decrement --m, pre decrement Eg: m=5 m=5 n=m++ n=++m m will be 6 m will be 6 n will be 5 n will be 6

(6)

Conditional Operator:

This operator is used to construct conditional expressions of the form.

Syn: exp1 ? exp2 : exp3

Where exp1, exp2 and exp3 are expressions. exp1 is evaluated first. If it true, then the exp2 is evaluated. Otherwise, the exp3 is evaluated.

Eg: a=10, b=5 x=(a<b) ? a : b

x will be assigned a value 10 Bit wise Operators:

Bit wise operators are used for manipulate of data values at bit level. Operator Meaning

& Bit wise AND

| Bit wise OR

^ Bit wise exclusive OR

~ One’s complement

<< Bit wise left shift >> Bit wise right shift

The expressions such as a&b, a|b, a^b are called bitwise expressions. Special Operators

Java supports some special operators such as instanceof operator and member selection(.) operator.

a. instanceof: The instanceof operator is an object reference operator. It return true, if the object on the left hand side is the instance of the class on the right hand side. This operator allows us to determine weather the object begins to a particular class or not.

Eg: if(stu1 instanceof student)

is true, if the stu1 belongs to the class student. Otherwise it is false.

b. Member Operator (or) Dot Operator: The dot(.) operator is used to access the instance (member) variables and methods of class objects.

Eg: stu1.sno=101; //reference to the variable sno stu1.result(); //reference to the member re4sult()

(7)

Java Operator Precedence and Associativity

Precedence Operator Type Associativity

15 () [] · Parentheses Array Subscript Member selection Left to Right 14 ++-- Unary post-incrementUnary post-decrement Right to left

13 ++ --+ -! ~ ( type ) Unary pre-increment Unary pre-decrement Unary plus Unary minus

Unary logical negation Unary bitwise complement Unary type cast

Right to left 12 * / % Multiplication Division

Modulus Left to right

11 +

-Addition

Subtraction Left to right

10

<< >> >>>

Bitwise left shift

Bitwise right shift with sign extension

Bitwise right shift with zero extension Left to right

9 < <= > >= instanceof

Relational less than

Relational less than or equal Relational greater than

Relational greater than or equal Type comparison (objects only)

Left to right

8 ==

!=

Relational is equal to

Relational is not equal to Left to right

7 & Bitwise AND Left to right

6 ^ Bitwise exclusive OR Left to right

5 | Bitwise inclusive OR Left to right

4 && Logical AND Left to right

3 || Logical OR Left to right

2 &: Ternary conditional Right to left

1 = += -= *= /= %= Assignment Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment Right to left

(8)

Conditional Control Statements (or) Decision Making Statements

The if statement may be implemented in different forms depending on complexity of conditions.  Simple if Statement

 if…else Statement

 Nested if…else Statement  else…if ladder

 Switch Statement

Simple if Statement

The general form is T

Syn: if(condition) {

Statement Block-x; F

}

Statement Block-y;

If the condition is true, then the SB-x will be executed, Otherwise SB-x will be skipped and SB-y will be executed. Eg: if(a>b) { big=a; } System.out.println(“big=”+big); If…else Statement

The general form is T F

Syn: if(condition) { Statement Block-x; } else { Statement Block-y; } Statement Block-z;

If the condition is true, then the SB-x will be executed and SB-y will not be executed. Otherwise, the SB-y will be executed and SB-x will not be executed. After executing one of the blocks the control transfers to SB-z. Eg: if(a>b) { big=a; } else { big=b; } System.out.println(“big=”+big); Conditio n SB-X SB-Y Conditio n SB-X SB-Y SB-Z

(9)

Nested if…else Statement

When a series of decisions are involved we use nested if…else statement. Syn: if(condition1) { F T if(condition2) { Statement Block-1; F T } else { Statement Block-2; } } else { Statement Block-3; } Statement Block-x;

The condition1 is evaluated first. If it is true, then the condition2 is evaluated. If the condition2 is true, then the SB-1 is executed. Otherwise, the SB-2 is executed and the control transfers to the SB-x.

If the condition1 is false, then the condition3 is evaluated and the control transfers to the to the SB-x.

Prog1: //a program to demo on ‘Nested if…else’ statement import java.util.*;

class big3 {

public static void main(String args[]) {

Scanner in= new Scanner(System.in)); int a,b,c,big;

System.out.println("Enter a,b and c values:"); a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); if(a>b) { if(a>c) big=a; else big=c; } else { if(b>c) big=b; else big=c; } System.out.println("big="+big); } } SB-2 SB-1 Condition 1 SB-3 Condition 2 SB-X

(10)

Else…if ladder

If multiple conditions are involved in our program we may use else…if ladder statement. The general form is Syn: if(condition1) T F Statement Block-1; else if(condition2) T F Statement Block-2; else if(condition3) Statement Block-3; T F ………. ………. T F else if(condition n) Statement Block-n; else

Default statement Block; Statement Block-x;

The conditions are evaluated from top to downwords. When the condition is true, the statement block associated with it is executed and the control transfers to the SB-x. When all the conditions become false then the default statement will be executed and the control transfers to the SB-x.

Eg: if(avg>=75) grade=”dist”; else if(avg>=60) grade=”first”; else if(avg>=50) grade=”second”; else if(avg>=35) grade=”third”; else grade=”fail”; System.out.println(“grade=”+grade); Switch Statement

The switch statement test the value of given variable or expression against a list of case values. When a case is found, a block of statements associated with that case is executed.

The general form is

Syn: switch(expression) { case value-1: Statement Block-1; break; case value-2: Statement Block-2; break; ……….. case value-n: Statement Block-2; break; default: Statement Block; }Statement Block-X; Cond 1 SB-1 Co nd2 SB-2 Co nd3 SB-3 Co ndn SB-n SB SB-X Expressi on SB-1 SB-2 SB-3 default SB-X

(11)

Here the expression is an integer (or) characters. val1, val2, …valn are the constants belongs to the expression. When the switch statement is executed, the value of the expression is successfully compared against val1, val2, …valn. If a case is found, the block of statements corresponding to that case is executed. The break statement at the end of each block causes exit from the switch statement. Eg: index=marks/10; switch(index) { case 10: case 9: case 8: grade=”dist”; break; case 7: case 6: grade=”first”; break; case 5: grade=”second”; break; case 4: grade=”third”; break; default: grade=”fail”; } System.out.println(“grade=”+grade);

LOOP control Statements (or) Iterative Statements

The process of repeatedly executing a block of statements for a number of times is known a looping. Java provides three looping control statements. They are

 while Statement  do Statement

 for Statement F

While Statement

The general form is T

Syn: while(test condition) {

Body of the lOOP; }

The while is an entry controlled loop. If the condition is true, the body of the loop is executed. After execution of body of the loop, the condition is evaluated once again and if it is true, the body is executed once again. This process is continuous until the condition become false and the control transfers to out of the loop.

Eg: sum=0; i=1; while(i<=10) { sum=sum+i; i++; } System.out.println(“Sum=”+sum); Test Condition

(12)

do Statement The general form is

Syn: do {

Body of the lOOP; }while(test condition);

The do…while is an exit control loop. The body of the loop is executed first. Ate the end of the loop the condition is evaluated. If the condition is true, the body of the loop executed once again. This process is continuous as long as the condition is true. When the condition becomes false, the loop will be terminated. Eg: sum=0; i=1; do { sum=sum+i; i++; } while(i<=10); System.out.println(“Sum=”+sum); For Statement The general form is

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

body of the lOOP; }

The execution of for statement is as follows:

 Initialization of the variable is done, by using assignment operator. Eg: i=1;

 The value of the variable is tested by using relational expression Eg: i<=10;

If the condition is true, the body of the loop is executed. Otherwise, the loop is terminated. When the body of the loop is executed, the control transfers to back to the for statement and the variable incremented by using increment operator.

Eg: i++;

And the new value of the variable is tested once again. If the condition is true, the body of the loop will be executed. This process in continuous as long as the condition is true.

Eg: for(i=1;i<=10;i++) {

System.out.println(“i=”+i); }

for statement allows decrement operator also Eg: for(i=10;9>=1;i--) { System.out.println(i); } Test Condition

(13)

Additional features of for lOOP

 More than one variable can be initialized at a time in the for statement. Eg: for(sum=0,i=1;i<=10,i++)

{

Sum=sum+i; }

 Like the initialization section, the increment section may also more than one part. Eg: for(n=1,m=50;n<=10;n++,m--)

{

………… ………… }

 The condition may also have any compound relation. Eg: sum=0;

for(n=1;n<=10&&sum<=50;n++) {

Sum=sum+n; }

 In the for loop one or more sections can be omitted . Eg: sum=0; i=1; for(;i<=10;) { sum=sum+i; i++; }

 Java supports nesting of for loop, that is one for with in another for statement. Eg: for(i=1;i<=3;i++) { for(j=1;j<=10;j++) { y=i*j; System.out.println(“ “+y); } System.out.println(“ “); }

(14)

Jumps in loops

Java permits a jump from one statement to end or beginning of a loop. a) jumping out of loop:

An early exit from a loop can be accomplished by using the break statement. When the break statement is encountered inside a loop, the loop is immediately exited and the program continuous with the statement immediately following the loop.

i=1; i=1; while(i<=10) do { { if(i==6) if(i==6) break; break; System.out.println(i); System.out.println(i); i++; i++; } }while(i<=10); ……… ………. ……… ……….

b) Skipping a part of a loop:

Like the break statement, java supports another similar statement called continue statement. The break statement causes the loop to be terminated. The use of continue statement in while, do and for loop causes the control to go directly to the condition and then to continue the iteration process. i=0; i=0; while(i<=10) do { { i=i+1; i=i+1; if(i==6) if(i==6) continue; continue; System.out.println(i); System.out.println(i); } }while(i<=10); ……… ………. ……… ……….

(15)

Java program structure // a program to find square root import java.lang.Math;

class Square {

public static void main(String args[]) {

double x=5; double y; y=Math.sqrt(x);

System.out.println(“The square root=”+y); }

}

A Java program may contain one or more sections as given below.

Documentation Section:

 This section uses a set of comment lines giving the name of the program, author, date and some other details.

 We can include comments begin with // (or) by starting with /* and ending with*/.

Package statement:

The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here are belongs to this package.

Import statement:

This statement similar to #include statement in ‘C’. Eg: import java.lang.Math;

This statement instructs interpreter to load the Math class contained in the package java.lang. Interface statement:

 An interface is a class but includes a group of method declarations.

 This is used only when we implement the multiple inheritance features in the program. Class definitions:

A Java program contains multiple class definitions. Classes are the primary and essential elements of a java program.

Main method class:

 Main method class is the essential part of a java program. A simple program may contains only this part.The main method creates objects of various classes and establishes communication between them.

Sample Java program

A simple Java program is as follows class Sample

{

public static void main(String args[]) { Documentation Section Package Statement Import Statement Interface Statement Class Definitions Main {

Main method definition }

(16)

System.out.println(“Java is better than C++”); }

}

Class declaration: The first line

class Sample

declares a class, everything must be placed inside a class. ‘Sample’ is a java identifier that specifies the name of the class. Class is a keyword and declares a new class definition.

Opening brace:

Every class definition in Java begins with an opening brace and ends a matching closing brace. The main line:

The third line

public static void main(String args[])

defines a method named main. Every Java program must include main() method.

 Public – The keyword public is an access specifier that declares the main method is accessible to all other classes.

 Static – The keyword static declares the method that belongs to entire class. The main must always be declared as static since the interpreter uses these method before any objects are created.

 Void – The type modifier void specifies that the main method doesn’t return any value.

 String args[] – Declares a parameter args[], which contains an array of objects of class type string. The output line:

The statement

System.out.println(“Java is better than C++”);

This is similar to the printf() statement of ‘C’. The println method is a member of out object, which is static data member of System class. This line prints the string

Java is better than C++ on the screen.

The method println always appends a new line character to the end of the string. Every Java statement must end with a semicolon.

Arrays:

An array is a collection of memory locations that can store same data items that share a common name. Arrays can be classified into two types. They are

 One dimensional arrays  Two dimensional arrays One dimensional array:

A list of items can be given one variable name using only one subscript is called a one dimensional array.

(17)

Creating an array:

Creating of an array involves three steps.  Declaring the array

 Creating memory locations  Initializing of arrays.

Declaring of array: Arrays in java may be declared in two forms. Form1: datatype arrayname[];

Form2: datatype[] arrayname; Eg: int a[];

int[] a;

Creating memory locations: After the declaration, we need to create the memory for arrays. Java allows to create arrays using new operator.

Syn: arrayname=new datatype[size]; Eg: a=new int[5];

Here, the variable a refers to an array of 5 integers. It is also possible to combine the declaration and creation of arrays.

Eg: int a[]=new int[5];

Initializing of arrays: After array creation we can put values into the array, this process is known as initialization. Syn: arrayname[subscript]=value; Eg: a[0]=10; a[1]=12; a[2]=14; a[3]=16; a[4]=18;

We can also initialize arrays automatically in the same way as the ordinary variables when they are declared.

Syn: datatype arrayname[]={val1, val2, ……… valN};

The array initializer is a list of values separated by commas and enclosed by braces. The compiler allocates enough space(size) for all the elements specified in the list.

Eg: int a[]={10,12,14,16,18}; Two dimensional array:

Java allows to define a table of items can be given one variable name using two subscripts is called two dimensional arrays. The table can be represented java as

a[2][3]

The first index specified the rows and the second index specified columns. A two dimensional array is stored in memory as

 We may create a two dimensional array with the statements.

int a[][]; //declaration

a=new int[2][3]; //creation (or)

int a[][]=new int[2][3];

This creates a table with 2 rows and 3 columns. i.e. it stores 6 integers.  A two dimensional may be initialize

(18)

 A quick way to initialize a two dimensional array is to use nested for loops. Eg: for(int i=0;i<3;i++)

{ for(int j=0;j<3;j++) { if(i==j) a[i][j]=1; else a[i][j]=0; } } Array length:

We can obtain the length of the array a using a.length. Eg: int a[]={10,12,14,16,18};

int size=a.length;

System.out.println(“List elements”); for(int i=0;i<size;i++)

System.out.println(a[i]);

Features of Object Oriented Programming system(OOPS)

There are many features to object oriented approach, some of the features are,  Class/Object  Encapsulation  Abstraction  Inheritance  Polymorphism Class/Object:

 An Object is an identifiable entity with some properties and behavior.

 For example, a table, a ball, a dog, a person etc, every thing will come under objects.

 Every object has properties and can perform certain actions. For example, a Person is an object, its properties are, name, age ,sex and etc.

 It is possible that some objects may have similar properties and actions. Such objects belong to same category called a ‘class’. For example raju, siva, ravi etc persons have same properties and actions. So they are all objects of same class person.

 Objects are variables of type class, once class has been defined, we can create any number of objects belonging to that class.

class person {

String name;

int age; properties of a person - variables void data( )

{

…….. actions done by a person - methods }

(19)

Encapsulation:

 The wrapping up of data and functions into a single unit is called as encapsulation”. The data cannot be accessed directly. We write variables and methods inside the class, class is binding them together. So class is an example for encapsulation.

 The variables in the class are declared as private, this means the variables are not directly available to any other class. The methods of class are declared as public, this means the methods can be called and used from any where outside the class. The only way to access the data is provided by the methods.

class person { String name; int age; void data( ) {

System.out.println(“\n Name is:”+name); System.out.println(“\n Age is:”+age); }

}

Data Abstraction:

 “Abstraction refers to the act of representing essential features without including the background details or explanations”.

 A class contains lot of data, but the user does not need the entire data, requires only some part of the available data. In this case we can hide the unnecessary data from the user. This is called abstraction.  For example, a bank clerk should see the customer details like acno, name and balance amount, he

should not be entitled to see the sensitive data like profit, loan and etc. class Bank

{

private int acno; private String name; private float balance; private float profit; private float loan;

public void display_clerk( ) { System.out.println(“Acc no:”+acno); System.out.println(“Name:”+name); System.out.println(“Balance:”+bal); } } Inheritance:

 “Inheritance is the capability of one class of things to inherit capabilities from another class”.  In OOP, the concept of inheritance provides the idea of reusability.

 This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes.

(20)

class A class B extends A

{ {

protected int a; private int c;

protected int b; public void method2( )

public void method1() {

{ }

} }

}

This means the variables a,b,c and the methods method1() and method2() are available to class B. Polymorphism:

 “Polymorphism is the ability to take more than one form”. The word poly originated from Greek word meaning many and morphism from a Greek word meaning form, and this ‘polymorphism’ means ‘many forms’.

 In OOP, polymorphism refers to identically named methods that have different behavior depending on the object they refer.

 Consider the following classes class A

{

void calc(int x) {

System.out.println("\n square value="+(x*x)); } } class B extends A { void calc(int x) {

System.out.println("\n cube value="+(x*x*x)); }

}

class poly {

public static void main(String args[]) { A ob1=new A(); B ob2=new B(); A ref; ref=ob1; ref.calc(2); ref=ob2; ref.calc(2); } }

(21)

CLASS Defining a Class

 A class is a user-defined data type with a template that serves to define its properties. Once the class has been defined, we can create “variables” of that type using declarations. These variables are known as instances of classes, which are the actual objects.

 The general form is

Syn: class classname[extends superclass] {

[fields declaration;] [methods declaration;] }

 Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables (or) members variables, because they are created whenever an object of the class is instantiated.

class student {

int sno; double age;

void getdata(int x,double y) { sno=x; age=y; } void putdata( ) {

System.out.println(“\n Name is:”+name); System.out.println(“\n Age is:”+age); }

}

Object Creation

 Creating an object is also referred as instantiating an object. Objects in java are created using the new operator. The new operator creates an object of specified class and returns a reference to that object.

student s1;

s1=new student();

Here the first declares a variable to hold the object reference and the second statement assigns the object reference to the variable. We can combined both the statements in one as

student s1=new student();

 The class members can be accessed using the dot(.) operator concerned with object. We cannot access the member variables and methods directly outside the class.

 We can assig values to the instance variables by using methods declared inside the class. s1.getdata(121,22.6);

Eg: class studetails

{ public static void main(String args[]) { student s1=new student();

s1.getdata(121,22.6); s1.putdata();

(22)

Access specifiers:

 An access specifier is a keyword that specifes how to access the members of a class or a class itself.  We can use access specifier before a class and its members. There are 4 access specifiers available in

java.

 Private: These members of a class are not accessible any where outside the class. They are accessible only within the class by the method of that class.

 Public: These members of a class are accessible every where outside the class. So any other program can read them and use them.

 Protected: These members of a class are accessible outside the class, but within the same directory.  default: If no access specifier is given by the programmer, then the java compiler uses a default

access specifier. The default members are accessible outside the class, but within the same directory. Constructors

 A constructor is used to initialize an object itself when it is created.  Constructors have the same name as the class itself.

 Constructors do not specify a return type, because they return the instance of the class itself. class student

{

int sno; double age;

student( ) //default constructor {

sno=100; age=22; }

student(int x,double y) //parameterized constructor { sno=x; age=y; } void putdata( ) {

System.out.println(“\n Name is:”+name); System.out.println(“\n Age is:”+age); }

}

class studetails {

public static void main(String args[]) {

student s1=new student(121,22.6); s1.putdata();

} }

 In the above program the given constructor is parameterized constructor with two parameters, int and double. These parameters will receive data from outside. So while creating objects, we pass a int and double number as,

student s1=new student(121,22.6);

Now, 121 is copied to first parameter x and 22.6 is copied to second parameter y. from there these two vales are copied into instance variables sno and age.

(23)

 When we do not pass any values at the time of object creation, then the default constructor is called. When the object is created as,

student s1=new student(); Now, s1 is initialized with 100 and 22.

 Difference between default and parameterized constructors

Default constructor Parameterized constructor It is useful to initialize all objects

with same data

It is useful to initialize each object with different data.

It does not have any parameters. It will have one or more parameters. When data is not passed at the

time of creating an object, default constructor is called.

When data is passed at the time of creating an object, parameterized constructor is called.

Methods:

 A method represents a group of statements that perform a task.  A method has two parts, method header and method body.

 Methods are declared inside the body of the class immediately after the declaration of instance variables. The general form of a method declaration is

Syn: type methodname(parameter-list) {

method body; }

Method declaration has four parts.  The name of the method.

 The type of the value the method returns.  A list of parameters.

 The body of the method.

 The method name is valid identifier.

 If the method doesn’t return any value, the return type will be void type.

 The parameter-list is always enclosed in a parenthesis, contains variable names and type of the values we want to give the method as input. The variables in the list separated by commas.

void getdata (int x, double y) {

sno=x; age=y; }

Static Members

If we want to define a member that is common to all the objects and accessed without using a particular object. Such member can be defined as

static int count;

static double mulop(double x, double y);

 The members that are declared as static are called as static members.

 Static variables are used when we want to have a variable common to all instances of a class.

 Like static variables, static methods can be called without using the object and also we by other classes.

For example the Math class of Java library defines many static methods. The method sqrt is a static method defined in Math class.

(24)

class Mathop {

static int mulop(*int x,int y) {

return(x*y); }

static int divop(int x, int y) { return(x/y); } } class Mathapp {

public static void main(String args[]) { int a=Mathop.mulop(5,6); System.out.println(“Multiplication=”+a); int b=Mathop.divop(a,5); System.out.println(“Division=”+b); } } Method Overloading

 In java, it is possible to create methods that have same name, but different parameters list and different definitions. This is called method overloading.

 Method overloading is used when objects are require to perform similar tasks but using different input parameters. When we call a method in an object, it matches the method name first and then the number and type of parameters is to decide which definition to execute. This process is known as polymorphism.

Eg: class Room {

float l,b;

Room(float x, float y) //Constructor1 { l=x; b=y; } Room(float x) //Constructor2 { l=b=x; } float area() { return(l*b); } }

Here we are overloading the constructor method Room( ).  An object representing a rectangle room will be created

Room r1=new Room(4.5,5.6);

 If the room is square we may create the object as Room r2=new Room(12.5);

(25)

The keyword ‘this’:

 ‘this’ is keyword that refers to the object of the class where it is used, that is to the present class.  All the class members by ‘this’. When an object is created to a class, a default reference is also

created internally to the object. So ‘this’ can refer to all the things of the present object.  Consider the following sample code

class sample {

private int x; sample( ) {

this(55); // call present class parameter constructor and send 55 this.access( ); // call present class method

}

sample(int a) {

this.x=a; //refer present class instance variable } void access( ) { System.out.println(“x value=”+x); } } class thisdemo {

public static void main(String args[]) {

sample s=new sample( ); }

}

Output: x value=55

 In this program when object is created the default constructor is invoked, then the statements this(55);

this.access( ); will be executed.

With the first statement parameterized constructor sample(int a) is called and 55 is passed to it. Here this.x=a; represents present class instance variable x. similarly to call the present class access( ) method, we use this.access( ) which displays the x value 55 as output.

Passing Objects to Methods

 We can also pass class objects to methods, and return objects from methods. Ex: Employee method1(Employee obj)

{

………….statments; return obj;

}

Here method1 accepts Employee class object. so reference of Employee class is declared as parameter in method1( ). We can also return the same object.

 Even objects are also passed to methods by value. This means, we send an object to a method, its copy will be sent to the method. Any modifications to the object inside the method will not affect the original copy outside the method.

(26)

 Consider the following program class Employee { int sal; Employee(int id) { this.sal=sal; } } class check {

void swap(Employee obj1,Employee obj2) { Employee temp; temp=obj1; obj1=obj2; obj2=temp; } } class passobjects {

public static void main(String args[]) {

Employee obj1=new Employee(6500); Employee obj2=new Employee(6700); check obj=new check();

System.out.println(“\n salary before calling”); System.out.println(obj1.sal+”\t”+obj2.sal); obj.swap(obj1,obj2);

System.out.println(“\n salary after calling”); System.out.println(obj1.sal+”\t”+obj2.sal); } } Output: C:\> javac passobjects.java C:\> java passobjects salary before calling

6500 6700

salary after calling 6500 6700

When we pass objects obj1 and obj2 to the method swap( ), a copy of the reference obj1 and obj2 are passed to the method to interchange. Outside the method, the original obj1 and obj2 will remain same. This is the effect of ‘pass by value’.

For this we can apply ‘pass by reference’, but java does not support pointers. So one possible solution is to use only one object and take two variables and interchange their values in the object.

(27)

class Employee { int sal1,sal2;

Employee(int basic1,int basic2) { this.sal1=basic1; this.sal2=basic2; } } class check {

void swap(Employee obj) { int temp; temp=obj.sal1; obj.sal1=obj.sal2; obj.sal2=temp; } } class passobjects{

public static void main(String args[]){

Employee obj1=new Employee(6500,6700); check ob=new check();

System.out.println("\n salary before calling"); System.out.println(obj1.sal1+"\t"+obj1.sal2); ob.swap(obj1);

System.out.println("\n salary after calling"); System.out.println(obj1.sal1+"\t"+obj1.sal2); }

} output

salary before calling 6500 6700 salary after calling

(28)

Strings:

 A sequence of characters is called a string and is implemented using two classes, namely String and StringBuffer.

 A java string is not a character array is not NULL terminated.  Strings may be declared and created as follows:

String stringname;

stringname=new String(“string”); Eg: String college;

college=new String(“sv arts”); These two statements may be combined as follows: Eg: String college=new String(“sv arts”);

 Like arrays, it is also possible to get the length of the string using the length method of the class String.

int m=college.length();

 Java strings can be concatenated using ‘+’ operator. String college=”sv”+”arts”;

 We can also create and use arrays that contained strings. The statement String name[]=new String(3);

String methods:

The String class defines a number of methods that allows to accomplish a variety of string manipulation tasks.

Method Call Task Performed

s2=s1.toLowercase s2=s1.toUppercase s2=s1.replace(‘x’,’y’) s1.equals(s2) s1.equalsIgnoreCase(s2) s1.length() s1.charAt(n) s1.compareTo(s2)

Converts the string s1 to all lowercase. Converts the string s1 to all uppercase. Replace all appearance of x with y. Return true, if s1 is equal s2.

Returns true, if s1=s2, ignoring the case of characters.

Gives the length of s1. Gives the nth character of s1.

Returns negative, if s1<s2. Returns positive, if s1>s2, and zero, if s1=s2.

StringBuffer class:

 A StringBuffer implements a sequence of characters. A StringBuffer is like a String, but can be modified in length and content. It creates 16 extra memory locations for a string.

 We can insert characters and substrings in the middle of the string (or) append another stringto the end.

Method Call Task Performed

s1.setCharAt(n,’x’) s1.capacity() s1.append(s2) s1.reverse() s1.insert(n,s2) s1.setLength(n)

Modifies the nth character to x. Gives the capacity of s1.

Appends the string s2 to the end of s1. Gives the reverse string of s1.

Inserts the string s2 at the position n in the string s1.

Set the length of the string s1 to n. if n<s1.length() it is truncated. If n>s1.length(), zero’s are added to s1.

(29)

INPUT AND OUTPUT Accepting Input from the Keyboard:

 A stream is required to accept input from the keyboard. A stream represents flow of data from one place to another place.

 A stream can carry data from keyboard to memory or from memory to printer or from memory to a file.

 There are two types of streams: input and output streams. Input streams are those streams which receive or read data coming from some other place. Output streams are those streams which send or write data to some other place.

 All streams are represented by classes in java.io (input and output) package. This package contains lot of classes, all of which can classify into two basic categories: input and output streams.

 System class is found in java.lang package and has three fields as shown below.

1. System.in: This represents input stream object, which by default represents standard input device i.e., keyboard.

2. System.out: this represents printstream object, which by default represents standard output device, i.e., monitor.

3. System.err: this field also represents printstream object, which by default represents monitor.

BufferedReader CLASS:

 The java.io.BufferedReader class is a subclass of java.io.Reader that you chain to another reader class to buffer character. This allows more efficient reading of characters and lines.

 In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character are byte stream.

Syntax: BufferedReader br = new BufferedReader (System.in);

 Will buffer the input from the specified file. Without buffering, each invocation of read( ) or readLine( ) could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

DataInputStream Reader:

 The InputStreamReader class serves as a bridge between the byte streams and character streams. It reads bytes from the input stream and translates them into characters according to a specified character encoding.

 An InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset.

 Each invocation of one of an InputStreamReader’s read( ) method may cause one or more bytes to be read from the byte-input stream.

 The general format to declare a InputStreamReader is,

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Accepting a single character from the keyboard:

 The read( ) method reads a single character from the keyboard but it returns its ASCII number, which is an integer, so we should convert it into char type by writing (char) before the method. char ch=(char)br.read( );

(30)

Accepting a string from the keyboard:

 The readLine( ) method accepts a string from the keyboard. String str=br.readLine( );

 The read( ) and readLine( ) methods fail due to some reasons, then it gives rise to a runtime error which is called by name IOException.

Accepting an Integer value from the keyboard:

 We have to follow these steps to accept an integer from the keyboard  First, we should accept the integer number from the keyboard as String.

String str=br.readLine( );

 Now, the number is in str, i.e in form of a string. This should be converted into an int by using parseInt( ) method of Integer class as,

int ix=Integer.parseInt(str);

The above two statements can be combined and written as int ix=Integer.ParseInt(br.readLine( ));

Accepting a Real value from the keyboard:

 Just like an integer value, we can also accept a float value in the following way. flaot fx=Float.ParseFloat(br.readLine( ));

 we can accept a double value from the keyboard with the help of following statement. double dx=Double.ParseDouble(br.readLine( ));

Accepting Different Types of Inputs in a Line:

 The StringTokenizer is useful to break a string into small pieces called tokens. First we have to receive a string from the keyboard, assume that they are separated by commas.

String str=br.readLine();

StringTokenizer st=new StringTokenizer(str,”,”);

 Collect the individual tokens from at using nextToken() method from StringTokenizer class. String token=st.nextToken();

SCANNER:

The scanner class is a class in java.util, which allows the user to read values of various types. A scanner object can read user input entered on the console or from a file. A scanner breaks its input into separate tokens, and then returns them one typically separated by white space, into values of different types.

Creating Scanners Obejects:

Whenever using scanners, be sure to include the proper import line: Import java.utill.Scanners;

We will create scanners in two ways:

1. to read from the console, use the following: Scanner input = new Scanner (System.in); 2. to read from a file, use the following:

(31)

Scanner Methods: METHOD DESCRIPTION nextBoolean ( ) nextInt( ) nextLong( ) nextDouble( )

nextString( )or next( ) nextLine( ) hasNextBoolean( ) hasNextInt( ) hasNextDouble( ) hasNextString( ) hasNextLine( )

Reads and converts next token to a boolean value Reads and converts next token to a integer value. Reads and converts next token to a long value. Reads and converts next token to a double value.

Reads and converts next token and returns it as a String. Reads utill the next new line and returns a string. Returns true if the next token is either”true” or “false” Returns true if the next token is an integer.

Returns true if the next token is a long.

Returns true if the next token is an real number

Returns true if there is at least one more token of input. System.out:

System.out is a PrintStream. System.out normally outputs the data on the console. This often used for console only programs like command line tools. This is also often used to print debug statements of from a program.

System:- It is a standard java class. It comes from the java.lang package. It is by default package. Out:- The class system contains static field named “out”.

So System.out refers to the value stored in that static field. The value System.out is an object of the class printStream from the standard java package java.io.

Println(): It is the instance method come from the PrintStream class.

So System.out.println() calls the “Println()” method associated with the “printStream” object reffered to by static field “out”.

To format and display the output, printf() method is available in PrintStraem class.This method works similar to printf() function in C. We know that System.out returns PrintStream class object, so to call the printf method, we can use, System.out.printf(). The following format characters can be used in printf(). %s – String %c – char %d – decimal integer %f – float number %O – Octal number %b, %B – Boolean value

%x,%X – Hexa decimal number %e,%E – number in scientific notation %n – new line character

Ex:- System.out.printf(“Salary = %f”,sal);

Here the string Salary= will be displayed as it is in the output. After this, we have %f, which represents a format character to display a float value, i.e., sal value. So if sal variable has 9400.25, then the out displayed by the above statement will be:

(32)

TYPE CASTING

The process of converting one data type into another data type is called type casting. The syntax is:

Syntax : datatype variable1=(type)variable2;

 Casting into a smaller type may result in a loss of data. Ex: int m=20;

byte n=(byte)m;

 Casting a floating point value into an integer will loss of decimal part. float m=23.5;

int x=(int)m;

here x will be assigned a value of 23 only.

//a program to find total and average by using type casting class Avg

{

public static void main(String args[]) {

int a,b,c,tot; float avg; a=2; b=3; c=6; tot=a+b+c;

avg=(float)tot/3; //type casting or avg=total/3.0; System.out.println(“tot=”+tot);

System.out.println(“avg=”+avg); }

Autoboxing and Unboxing

 When Java automatically converts a primitive type like int into corresponding wrapper class object e.g. Integer than its called autoboxing because primitive is boxed into wrapper class while in opposite case is called unboxing, where an Integer object is converted into primitive int.

 All primitive types e.g. byte, short, char, int, long, float, double and boolean has corresponding wrapper class e.g. Byte, Short, Integer,Character etc and participate in autoboxing and unboxing. Since whole process happens automatically without writing any code for conversion its called autoboxing and auto unboxing.

Important point about Autoboxing and Unboxing in Java

1) Compiler uses valueOf() method to convert primitive to Object and uses intValue(), doubleValue() etc to get primitive value from Object.

2) During autoboxing boolean is converted to Boolean, byte to Byte, char converted to

Character, float changes to Float, int goes to Integer, long goes to Long and short converts to Short, while in unboxing opposite happens like Float to float.

(33)

UNIT –II:

INHERITANCE & INTERFACES

Inheritance is done using the key words "extending" and "implementing" B

enefits of inheritance:

1. Code reuse: If class A is the base and class B is derived from A, you need not write A's code in B. If you say B is inherited from A, all the code of A is automatically included for B. This benefit will be of much use situations like Class C being derived from B. You need not even know the parent of B. The key word used here is "extending"

2. However code reuse is not of great importance, though convenient. More important is that you have a logical design of classes from the most general level to lesser general level and so on.This relation reflects the actual heirarchical positioning of the class in the overall design.

3.With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.

4.Interfaces are classes that essentially have method names but no definitions. So you can not create objects from such Interfaces.We should use Inheritance in such cases to create an instantiable class for those Interfaces. This process is referred by the keyword "implementing".

5.In java, you can extend from only one instantiable class, but you can implement from one or more interfaces.

6. With inheritance, we can create a reference to the base class, but assign a derived class object to that reference. This concept is very widely used in java.

Inheritance

 The mechanism of deriving a new class from an old class is called inheritance. The old class is known as the base class (or) superclass (or) parent class. The new class is known as subclass (or) derived class (or) child class. Java supports this concept, this is basically done by creating new class, reusing the properties of existing class.

 The inheritance allows inheriting all the variables and methods of their base class. Inheritance may take different forms.

 Single Inheritance (Only one superclass)  Multiple Inheritance (Several Superclasses)

 Hierarchical Inheritance (One superclass many subclasses)  Multilevel Inheritance (Derived from derived class)

A B B D A C C B D A A B C

(34)

Defining a Subclass

Syn: class subclassname extends superclassname {

variables declaration; members declaration; }

The keyword extends signifies that the properties of superclass extends to the subclass. The subclass will contains its own variables and methods as well as those of the superclass.

Eg: class Room //Base class { int l,b; Room(int x, int y) { l=x; b=y; } int area() { return(l*b); } }

class Office extends Room { int h;

Office(int x, int y, int z) {

super(x,y); //Passing values to superclass h=z; } int volume() { return(l*b*h); } } Class Singleinh {

public static void main(String args[]) {

Office f1=new Office(5,6,7); int area=f1.area(); int volume=f1.volume(); System.out.println(“Area=”+area); System.out.println(“Volume=”+volume); } }

 The subclass office includes three member variables l, b and h and two methods area() and volume().  The constructor in the derived class uses the super keyword to pass values that are required by the

base class constructor.

 The object f1 of the derived class office calls the method area() defined in superclass as well as the met6hod volume() defined in the subclass itself.

(35)

Subclass Constructor

 A subclass constructor is used to construct the member variables of both the subclass and superclass. The subclass constructor uses the keyword super to invoke the constructor of superclass.

 The constructor used with the keyword super.

i. super may only be used with in a subclass constructor method.

ii. The call to the superclass constructor must appear as the first statement with in the subclass constructor.

iii. The parameters in the keyword super must match the order and type of the member variables declared in the superclass.

Multilevel Inheritance

A chaild class can inherits the properties from parent class. The parent class can inherit the properties from grant parent is called Multilevel inheritance.

A derived class with multilevel base class is derived as follows: class A

{

……….. ………..

} Grand Father Superclass

class B extends A { ……….. Father intermediate Superclass ……….. } Child Subclass class C extends B { ……….. ……….. }

This process may be extended to any number of levels. The class C can inherit the members of both classes A and B.

Final Variables and Methods

The members of superclass can be overridden in subclasses. We can prevent this by declaring them as final using the keyword final a modifier.

Eg: final int SIZE=100; final void display(); {

…………. …………. }

Making a method final ensures that the functionality defined in this method will never be modified. Similarly the value of a final variable never be change. Final variables, behave like class variables and they do not take any space on individual objects of the class.

A

B

(36)

Final Classes

 A class that cannot be subclass is called a final class.  In java by using the keyword final as

final class A {

…………. …………. }

Any attempt to inherit this class will cause an error and the compiler will not allow it. Declaring a class final to prevent any unwanted extension to that class.

Abstract Classes and Methods

 Making a method final to ensure that the method is not redefined in subclass.

 Java allows to make a method must always be redefined in a subclass by using a modifier keyword abstract in the method definition.

abstract class Shape {

…………. ………….

abstract void draw(); //Method declaration ………….

}

While using abstract classes, we must follow following conditions.  We cannot use abstract classes to create objects directly.

Eg: Shape s1=new Shape(); Is a illegal statement.

 The abstract method of an abstract class must be defined in its subclasses. Eg: class Circle extends Shape

{

………

void draw() //Method defined {

……… }

……… }

(37)

Interfaces

 Java provides an alternate approach known as interfaces to support the concept of multiple inheritance.

 A class can implement with more than one interface to support multiple inheritance.

 An interface is basically a kind of class, it contains methods and variables but with a major difference. The difference is the interfaces define only abstract methods and final variables.

 The interface do not specify any code to implement these methods, it is the responsibility of the class that implement an interface to define the code for implementation of these methods.

 The syntax for defining an interface is similar to that for defining a class. Syn: interface interfacename

{

Variables declaration; Methods declaration; }

Here, interface is the keyword and interfacename is any valid java identifier.  Variables are declared in the interface

final datatype variablename=value;

 Methods declaration will contain only a list of methods without any body statement. public returntype methodname(arguments_list);

Eg: interface item {

static final int CODE=1001;

static final string NAMEe=”tomy”; public void display();

} Extending interfaces:

Like classes, interfaces can also be extended. That is an interface can be sub interface from other interfaces. The new sub interface will inherit all the members of super interface. This is can be achieved by using the keyword extends.

interface name2 extends name1 {

Body of name2; }

Eg: interface item {

static final int CODE=1001; static final string NAME=”tomy”; public void display();

}

interface itemcost extends item {

public void showcost(); }

The interface itemcost will inherit both the constants code and name into it. We can also extends several interfaces together into a single interface.

interface item

{ ………….

…………. }

(38)

interface discount {

…………. …………. }

interface itemcost extends item,discount {

…………. …………. }

Implementing interface:

Interfaces are used as “superclasses” whose properties are inherited by classes. Therefore it is necessary to create a class that inherits the given interface.

Syn: class classname implements interfacename {

body of the class; }

Here, the class classname implements the interface interfacename. A class can also extends another class while implementing interfaces.

class classname extends superclassname implements interface1, interface2, …. {

body of the class; }

When a class implements with more than one interface, they must be separated by commas. The implementation of interfaces can take various forms as follows.

Interface Class Interface

Implements Extends Extends

Class Class

Extends Extends Implements

Class Class

Interface Interface Interface

Extends Implements

Interface Implements

Class Class Class

(Multiple Inheritance) A C B A C B D E B C A A B C D

(39)

// a program on multiple inheritence import java.util.*;

class student //base class {

int sno; double age;

Scanner in=new Scanner(System.in); void getdata()

{

System.out.println("Enter student number and age"); sno=in.nextInt();

age=in.nextDouble(); }

void putdata() {

System.out.println("student number :"+sno); System.out.println("Student age: "+age); }

}

class marks extends student //derived class {

double m1,m2,m3; void getmarks() {

System.out.println("Enter 3 subject marks"); m1=in.nextDouble(); m2=in.nextDouble(); m3=in.nextDouble(); } void putmarks() { System.out.println("Marks in 3 subjects"); System.out.println("subject 1:"+m1); System.out.println("subject 2:"+m2); System.out.println("subject 3:"+m3); } } interface sports {

final double swt=6.5; //final member variables void putsports(); //abstract method

}

class result extends marks implements sports {

String res; double tot;

public void putsports() {

System.out.println("sports marks="+swt); }

(40)

void getresult() {

tot=m1+m2+m3;

if(m1>=35 && m2>=35 && m3>=35) res="pass"; else res="fail"; } void putresult() { System.out.println("Result="+res); System.out.println("Total Makrs="+tot); } } class multiple {

public static void main(String args[]) {

result stu=new result(); stu.getdata(); stu.getmarks(); stu.getresult(); stu.putdata(); stu.putmarks(); stu.putresult(); } } Packages

A package is a collection of classes and interfaces. In java, all reusable code is put into packages. Java packages are classified into two types. The first category is known as java API packages and second is known as user defined packages.

Java API packages:

Java API provides a large number of classes grouped into different packages according to functionality. The following figure shows the packages that are frequently used in the program.

Java

lang io util awt net appl

Referências

Documentos relacionados

Segundo o diretor da escola Manoel da Costa Cirne, refe- rência no bairro, os moradores reconhecem a necessidade da cultura, do esporte e do lazer como forma de

Já o peso médio das presas aumentou com a temperatura, o que poderá ser o resultado do aumento de consumo de lagomorfos (com maior biomassa) e de insetívoros nas regiões com uma

Serem as raparigas a demonstrar menores níveis de bem-estar psicológico tanto no que respeita ao bem-estar psicológico como no que concerne às dimensões deste vai ao

Although the efficiency of the local search method can be improved by using a set in which the variables representing the installation descision are fixed, the calculation time

Com base nas necessidades existentes nos serviços paroquiais e arquidiocesanos mostrados por meio da coleta de campo quantitativa, foram enviados e-mails contendo o

The independent variables are: number of members (members), percentage of independent and inside directors (pct_independent and pct_inside), percentage of female directors

Thus it is concluded that the study variables in Model 1 are determinants of debt, which was not observed in model 2, and that the income variables

mente, em estudos foram utilizados testes in vitro como a dosagem de mediadores infl amatórios no sangue total humano e linhagens celulares que respondem a todos os