csevoc.webnode.com …  · web viewunit - i. object-oriented programming and java. who developed...

91
UNIT - I OBJECT-ORIENTED PROGRAMMING AND JAVA 1. Who developed Java language? A) Java was developed by James Gosling at Sun Microsystems in 1995. 2. Write a simple java program to display “hello world”? A) class Simple { public static void main(String args[ ]) { System.out.println(“hello world”); } } 3. What are the commands for compilation and execution of java programs? A) To compile: javac <programname.java> Ex: javac simple.java To execute: java <classname> Ex: java simple 4. What is java Byte code? A) Java Bytecode: Java bytecode is the form of instructions that the Java virtual machine executes. Each bytecode opcode is one byte in length, although some require parameters, resulting in some multi-byte instructions. 5. What is JVM?

Upload: others

Post on 18-Mar-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

UNIT - I

OBJECT-ORIENTED PROGRAMMING AND JAVA

1. Who developed Java language?A) Java was developed by James Gosling at Sun Microsystems in 1995.

2. Write a simple java program to display “hello world”?A) class Simple

{ public static void main(String args[ ])

{ System.out.println(“hello world”); }

}

3. What are the commands for compilation and execution of java programs?A) To compile: javac <programname.java>

Ex: javac simple.javaTo execute: java <classname>

Ex: java simple

4. What is java Byte code?A) Java Bytecode: Java bytecode is the form of instructions that the Java virtual machine executes. Each bytecode opcode is one byte in length, although some require parameters, resulting in some multi-byte instructions.

5. What is JVM?A) JVM: JAVA VIRTUAL MACHINE (JVM) is virtual machine that can execute Java bytecode. It is the code execution component of the Java software platform.

6. What is JRE?A) JRE: JAVA RUNTIME ENVIRONMENT (JRE) is a software framework developed by oracle Corporation, which runs regardless of the computer architecture. It provides the Java virtual machine and a large library which allows to run applications written in the java programming language.

7. What is JIT compiler? JIT : Just – in – time compiler is a dynamic compiler having a compilation method to improve the runtime performance of computer programs based on byte code.

Page 2: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

8. How java is platform independent?A) Platform means an operating system such as windows, xenix, linux,etc.,If a java program is compiled, it is compiled into platform independent byte code. This byte code can run on any platform. Hence we can say that the java is platform independent.

9. What are applets? Applets: Applets are small java programs that are primarily used in internet computing. They can be transported over the internet form one computer to another computer and run using AppletViewer or by any Webbrower that supports java. It can perform arithmetic operations, display graphics, play sounds, accept user input, create animation, and play interactive games etc.,

10. What is a ‘Class’? and What is Sub – class?A) Class: A class is a collection of objects of similar type. It is a template from which objects are created.Sub Class: A class which is derived from another class is called as sub class or derived class.

11. What is an Object? Write the characteristics of an object?A) Object is a basic runtime entity having state and behavior. They may represent a person, a

place, or any item that the program may handle.The characteristics of an object are:

a) State: Represents the data of an objectb) Behavior: Represents the behavior of an object.c) Identity: The unique ID is used internally by the JVM to identify each object uniquely.

12. What is instance variable?A) Instance Variable: A variable that is created inside the class is known as an instance variable. These variables are only declared and therefore no storage space has been created in the memory. Instance variables are also known as member variables.

13. What is a ‘Method’? and write the advantages of methods?A) METHOD: A Java method is a collection of statements that are grouped together to perform an operation.The advantages of a method are:

Code reusability. Code optimization.14. What is Expansion of WORA?

A) WORA: Write Once, Run Anywhere.B)

Long answer questions:

15. Explain briefly class, public, static, void, main, string[ ], and system.out.println( ) ?A) Class: A class is a collection of objects of similar type. It is a template from which

Page 3: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

objects are created. It is used to declare a class in java.public: public is an access modifier which represents visibility, it means it is visible to all.static: static is a keyword, if we declare any method as a static, it is known as static method.

void: is the return type of the method, it means it doesn’t return any value.main: Represents the startup of a program.

String args[]: Is used for command line argument.System.out.println( ): Is used print a statement on the console.

16. Write the Features of Java?A) Features of Java:1.Object Oriented: In java everything is an Object. Java can be easily extended since it is based on the Object Model.2.Platform Independent: Platform means an operating system such as windows, xenix, linux,etc., If a java program is compiled, it is compiled into platform independent byte code. This byte code can run on any platform. Hence we can say that the java is platform independent.3. Simple: Java is designed to be easy to learn. If we understand the basic concept of OOP java would be easy to master.4,Secure: With java’s secure feature it enables to develop virus – free, tamper – free systems. Authentication techniques are based on public – key encryption.5.Architetural – Neutral: Java compiler generates an architecture – neutral object file format which makes the compiled code to be executable on many processors with the presence Java runtime system.6. Portable: We may carry the java byte code to any platform.7. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.8.Multi – threaded: With java’s multi-threaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.9.. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored any where. The development process is more rapid and analytical since the linking is an incremental and light weigh process.10.High Performance: With the use of Just – In – Time compilers Java enables high performance.11.Distributed: Java is designed for the distributed environment of the internet.12. Dynamic: Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run – time.

17. Write the Features of OOP?

Page 4: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

A) The features of Object Oriented Programming are:I. Abstraction

II. EncapsulationIII. PolymorphismIV. Inheritance

1. Abstraction: Hiding the certain details and only show the essential features of the object.2. Encapsulation: The wrapping up of data and methods into a single unit (called class) is known as encapsulation.3. Polymorphism: Polymorphism means the ability to take more than one form is called Polymorphism.4. Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. Inheritance provides the idea of reusability.

18. A record contains employee number(empno), employee name(ename) and salary (sal) so, write a program to display the details of three employees?

A)class Employee{int empno, sal;String ename;void InsertRecord(int r, String n, int s){empno =r;ename=n;sal=s;}void DisplayInformation(){System.out.println(empno+" " +esname+" "+sal);}public static void main(String args[]) {Employee e1=new Employee();Employee e2=new Employee();Employee e3=new Employee();e1.InsertRecord(101,"Venkat",50000);e2.InsertRecord(102,"Shiva",30000);e3.InsertRecord(103, "Ganesh",20000);e1.DisplayInformation();e2.DisplayInformation();e3.DisplayInformation();

} }

Page 5: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Output:101 Venkat 50000102 Shiva 30000103 Ganesh 20000

UNIT – IITHE JAVA PROGRAMMING LANGUAGE

Page 6: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

1. What is a ‘Class’? and What is Sub – class?A) Class: A class is a collection of objects of similar type. It is a template from which objects are created.

Sub Class: A class which is derived from another class is called as sub class or derived class.

2. What are Key Words?A) KEY WORD: Keywords are reserved words that are predefined having a specific meaning which tell the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case.

Ex: break, double, import, public, throws

3. What is an Identifier?A) IDENTIFIER: Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must be composed of letters, numbers, the underscore_ and the dollar sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.

4. What is a Literal?A) LITERAL: Literals in Java are a sequence of characters (digits, letters and other characters)that represent constant values to be stored in variables. Java language specifies five major types of literals. They are

1 Integer literals 2 Floating point literals3 Character literals4 String literals5 Boolean literals

5. What are comments or Write about Documentation Comments in Java?A) Comments: Comments are descriptions that are added to a program to make code easier to

understand. The compiler ignores comments.Java supports three comment styles.Block style comments begin with /* and terminate with */ that spans multiple lines.Line style comments begin with // and terminate at the end of the line. Documentation style comments begin with /** and terminate with */ that spans multiple lines.

6. What are four main primitive data types in Java?a) The Four Primitive Data Types in JAVA are:

Integer: byte, short, int, and long. Floating Point: float and double Character: char Boolean: variable with a value of true or false.

7. What are White Space characters?A) White space consists mostly of the space character that we produce by hitting the space bar on out keyboard and that is commonly used to separate words in sentences. There are 4 other white space characters in Java, the horizontal tab, the form feed, the carriage return, and the linefeed.

Page 7: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

8. What is mixed mode?A) When one operand is real and another is integer, the expression is called mixed-mode arithmetic expression.

9. What is the difference between ++i and i ++ ?A) ++i : This is called prefix increment. A prefix operator first adds 1 to the operand and then the result is assigned to the variable. i++ : This is called postfix increment. A postfix operator first assigns the value to the variable on left and then increments the operand.

10. What is the difference between - -i and i - - ?A) - - i : This is called prefix decrement. A prefix operator first decrements 1 to the operand and then the result is assigned to the variable. i - - : This is called postfix decrement. A postfix operator first assigns the value to the variable on

left and then decrements the operand.

11. What is conditional operator?A) CONDITIONAL OPERATOR: (? :) Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as :

variable x = (Boolean expression)? Expr1: Expr2Boolean Expression is evaluated first and if it is true expression1 is assigned to the variable x.if it is false expression2 is assigned to the variable x.

12. What is a Method?A) Method: A Java method is a collection of statements that are grouped together to perform an operation. Methods are declared inside the body of the class but immediately after the declaration of instance

variables. The general form of a method declaration is:

Syntax: type method_name (parameter-list){method-body;

}13. What is a constructor?CONSTRUCTOR: A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

14. What is a Destructor?A) DESTRUCTOR: It is possible to define a method that will be called just before an object's final

destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Page 8: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Long Answer Questions

1. Write about separators in Java?A)

2. Explain Arithmetic Operators with an Example?A) Arithmetic Operators: Arithmetic Operators are used to perform arithmetic operations on two operands.

Ex: a and b are integer variables and assigned a=5 and b=3 thenOperator Purpose Arithmetic

ExpressionResult

+ Addition a+b 8- Subtraction a-b 2* Multiplication a*b 15/ Division a / b 1% Remainder after

integer divisiona%b 2

3. Explain Relational Operators with examples?A) Relational Operators: Relational Operators: There are six relational operators supported by Java

language. These returns result in the form of ‘true’ or ‘false’.

Ex: a, b and c are integer variables and assigned 3, 5 and 10 respectively.

Operator PurposeRelational Expression

Result

SEPARATORS PURPOSE

Parentheses ( )Encloses arguments in method definitions and calling; adjusts precedence in arithmetic expressions; surrounds cast types and delimits test expressions in flow control statements

Braces { } defines blocks of code and automatically initializes arraysBrackets [ ] declares array types and dereferences array valuesSemi colon ; terminates statements

Comma , separates successive identifiers in variable declarations; chains statements in the test, expression of a for loop

Period . Selects a field or method from an object; separates package names from sub-package and class names

: Used after loop labels

Page 9: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

= = is Equal to c = = 10 False

! = is Not equal to a != b True

> is Greater than a>b False

< is Less than (a+b)<c True

> = is Greater than or equal to a>=3 True

< = is Less than or equal to b < = a False

4. Explain the Logical Operators with examples?A) The logical operators are &&(and) , ||(or) and !(not).

&& (and) : If both operands are true then the logical &&(and) is true

a B a && b0 0 00 1 01 0 01 1 1

|| (or) : If either operand is true then the logical ||(or) is true.

a b a || b0 0 00 1 11 0 11 1 1

! (not) : It negates the operand.

a !a0 11 0

Ex: a, b and c are integer variables and assigned 3, 5 and 10 respectively.

Page 10: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Operator Purpose Expression Result

&& And (a>b) && (c>a) False

|| Or (a>b) || (c>a) True

! Not !(a>8) True

5. Explain Bitwise and Bitshift operators in Java?A) BITWISE and BIT SHIFT OPERATORS: bitwise and bit shift operators are used to manipulate the contents of variables at a bit level according to binary format.

Symbol Name of the Operator Example~ Unary bitwise complement ~op2& Bitwise AND op1 & op2| Bitwise inclusive OR op1 | op2^ Bitwise exclusive OR op1 ^ op2<< Signed left shift op1 << op2>> Signed right sift op1 >> op2>>> Unsigned right shift op1 >>> op2

6. Explain about assignment operators in a Java?A) ASSIGNMENT OPERATORS: Assignment operators are used to assign the value of an expression. The simple assignment operator is ‘=’ (the equals symbol).

Operator Expression Equivalent

+= x+=a x=x+a

-= x-=a x=x-a

*= x*=a x=x*a

/= x/=a x=x/a

%= x%=a x=x %a

<<= x<<=2 x=x << 2

>>= x>>2 x=x >> 2

&= x&=2 X = x & 2

^= x ^= 2 x = x ^ 2

|= x |= 2 x = x | 2

7. Explain about Increment and Decrement Operators in Java?

Page 11: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

A) INCREMENT AND DECREMENT OPERATORS: There are two Increment or decrement operators   ++ and --. The operators ++ adds 1 to the operand while – subtracts 1. Both are unary operators and are used in the following form:

++m; or m++;--m; or m--;

++i : This is called prefix increment. A prefix operator first adds 1 to the operand and then the result is assigned to the variable. i++ : This is called postfix increment. A postfix operator first assigns the value to the variable on left and then increments the operand.

- - i : This is called prefix decrement. A prefix operator first decrements 1 to the operand and then the result is assigned to the variable. i - - : This is called postfix decrement. A postfix operator first assigns the value to the variable on

left and then decrements the operand.

Example

x = 5;y = ++x;System.out.println(y);

prints 6, but

x = 5;y = x++;System.out.println(y);

prints 5

When we write i++ we're using shorthand for i = i + 1.

When we say i-- we're using shorthand for i = i - 1.

Example

x = 5;y = --x;System.out.println(y);

prints 4, but

x = 5;y = x--;

Page 12: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

System.out.println(y);

prints 5

8. Write about precedence of operators?A) Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. If the precedences are equal perform from left to right.

Category  Operator  Associativity 

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Page 13: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Comma , Left to right

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. See the following example.

Expression ResultX=5+3*2 X=11X=(5+3)*2 X=16X=8+4/(3-1) X=10X=8/4/2 X=1

9. Write a java method to find the minimum of value in given two values?A) import java.util.*;

import java.io.*;class TestMin{public static void main(String args[ ]){int i=5, j=2,k=min(i,j);System.out.println("The minimum between "+i+"and"+j+"is"+k); }public static int min(int num1, int num2) { int result; if (num1<num2) result = num1;else result=num2; return result;}}

Page 14: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

UNIT – IIICONTROL STATEMENTS AND ARRAYS

1. What is conditional branching?A) Conditional Branching: When a branching is based on a particular condition, it is called conditional branching.

2. What is unconditional branching?A) Unconditional Branching: If branching takes place without any condition, it is called unconditional branching.

3. Write the Syntax of if statement?A) if statement: if statement is used to control the flow of execution of statements.

Syntax : if (test expression){

Statement _block;}statement x;

The statement _block may be a single statement or multiple statements. If the test expression is ‘true’, the statement_block will be executed, otherwise the statement block will be skipped and the control flows to the immediately following the statement block.

4. Write a program to find the bigger value in given two values?A. // finds larger value between two values

import java.util.Scanner; class larger{ public static void main(String args[])

Page 15: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

{ int x, y ,big; System.out.println("Enter two integers "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); big = x;

if(big<y) big = y;System.out.println("big="+big);

} }

5. What is switch statement?A) Switch Statement: The switch statement tests the value of a given variable against a list of value and when a match is found, corresponding block of statements associated with the case will be executed. If none is matched ‘default’ block will be executed.

6. What are nested if statements?A) An if statement is in another if statement are called nested if statements.

7. What are various loop statements?A) The loop statements are

I. The while statementII. The do-while statement

III. The for statement

8. What is a break statement?A) break: If the break statement encountered in a loop, the loop immediately exited and the program continues with the statement immediately following the loop.

Syntax: break;

9. What is a continue statement?A) continue: The ‘continue’ statement causes the loop to be continued with the next iteration after skipping any statement in between and continue with the next iteration.

Syntax: continue;

10. What is an Array?A) Array: An array is a collection of similar type of data elements which are stored in consecutive memory locations under a common variable name.

Page 16: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Long Answer questions:

1. Write about if and if – else statements?A) if statement: if statement is used to control the flow of execution of statements.

Syntax : if (test expression){

Statement _block;}statement x;

The statement _block may be a single statement or multiple statements. If the test expression is ‘true’, the statement_block will be executed, otherwise the statement block will be skipped and the control flows to the immediately following the statement block.Ex: if (a>b) big = a;

if …… else statement: The if…..else statement is an extension of the simple if statement. If the test expression is true then statements under if will be executed else statements under else will be executed.

Syntax: if (test expression) {

true block statements; } else { false block statements; }

Ex: if (a>b) big = a; else big = b;

2. Write about switch statement?A) Switch Statement: The switch statement tests the value of a given variable against a list of value and when a match is found, corresponding block of statements associated with the case will be executed. If none is matched ‘default’ block will be executed. The ‘break’ statement at the end of each block signals the end of a particular case causes an exit from the switch statement, transferring the control to the statement immediately following the switch.

Syntax: switch(expression){case value: block1;

break;case value: block2;

Page 17: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

break;case value: block3;

break;----------------------------------------default: default block;

break;}

Sample program with switch.. case is as follows.

import java.util.Scanner; public class SwitchExample { public static void main(String args[]) { System.out.println("enter a code"); Scanner in = new Scanner(System.in);

int code = in.nextInt();

switch(code) { case 1 : System.out.println("first class"); break; case 2: System.out.println("second class"); break; case 3 : System.out.println("third class"); break; default : System.out.println("fail"); } }}3. Write a program to find biggest of three values?

Page 18: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

// finds biggest value among three values

import java.util.Scanner;

class biggest

{

public static void main(String args[])

{

int x, y, z,big;

System.out.println("Enter three integers ");

Scanner in = new Scanner(System.in);

x = in.nextInt();

y = in.nextInt();

z = in.nextInt();

big = x;

if(big<y) big = y;

if(big<z) big = z;

System.out.println("biggest="+big);

} }

4. Write about while loop with an example?A) 1. while statement: The while statement is an “entry – controlled” loop. The test condition is evaluated first and if the condition is true, then the body of the loop is executed this process repeated until the test condition is false. If, the test condition is false then the control is transferred to the statement immediately following the loop.

Syntax: Initialization; while(test_condition) {

Body of the loop; }

Page 19: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Ex: //to find the factorial by using while loopimport java.util.Scanner;class Factoria{public static void main(String args[]){int i,f=1,n;System.out.println("Enter an Integer:");Scanner in = new Scanner(System.in);n = in.nextInt();i = 1;while(i<=n){f*=i;++i;}System.out.println("Factorial of"+n+"is" +f);}}

Output:Enter an Integer:5Factorial of 5 is 120

5. Write about do – while loop with an example?A) do – while loop: The do-while loop is bottom tested loop. The body of the loop will be executed at least once even the condition is false because the Condition will be evaluated after execution of the loop body.

Syntax: initialization;do{

Body of the loop;}while(test_condition);

Ex: //prints 5 natural numbers 1,2,3,4,5 by using do whileclass Natnumbers{public static void main(String args[]){int i;i=1;do{System.out.println(i++);}while(i<=5);}}

Page 20: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Output: 12345

6. Write about for loop with an example?A) for loop: The execution of for loop is as followsa) Initialization of the control variables is done first.b) The value of the control variable is tested using the test condition. If the test condition is true the body of the loop will be executed otherwise loop will be terminated.c) When the body of the loop is executed, the control is transferred back to the for statement and it will be updated.

Syntax: for(exp1;exp2;exp3) {

Body of the loop }

exp1 : Initialization Expression.exp2 : Condition or Control Expression.exp3 : Update Expression.

Ex: //To find the sum of n natural numbersimport java.util.Scanner;class Sumnnos{public static void main(String args[]){int i,s=0,n;System.out.println("Enter an integer:");Scanner in=new Scanner(System.in);n=in.nextInt();for(i=1;i<=n;i++){s+=i;}System.out.println("sum of "+n+"natural numbers is "+s);}}

Output:Enter an integer: 5sum of 5 natural numbers is 15

Page 21: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

7. Write a program to find factorial value of a given number?A) // program to find the factorial by using while loop

import java.util.Scanner;class Factoria{public static void main(String args[]){int i,f=1,n;System.out.println("Enter an Integer:");Scanner in = new Scanner(System.in);n = in.nextInt();i = 1;while(i<=n){f*=i;++i;}System.out.println("Factorial of"+n+"is" +f);}}

Output:Enter an Integer: 8Factorial of 8 is 40320

8. Write a program to find the natural sum of a given number?A) //To find the sum of n natural numbersimport java.util.Scanner;class Sumnnos{public static void main(String args[]){int i,s=0,n;System.out.println("Enter an integer:");Scanner in=new Scanner(System.in);n=in.nextInt();for(i=1;i<=n;i++){s+=i;}System.out.println("sum of "+n+"natural numbers is "+s);}}

Output:Enter an integer: 10Sum of 10 natural numbers is 55

Page 22: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

9. Write a program to find the minimum of a given array?A) //Program to find the Minimum value of a given arrayimport java.util.Scanner;class Minofary{public static void main(String args[]){int i, min,n;int a[]=new int[10];System.out.println("Enter the size of the array: ");Scanner in=new Scanner(System.in);n=in.nextInt();System.out.println("Enter the elements for array: ");for(i=1;i<=n;i++){a[i]=in.nextInt();}min=a[1];for(i=1; i<=n;i++){if(min>a[i]) min=a[i]; }System.out.println("Minimum value in the given array is: "+min);}}Output:Enter the size of the array: 5Enter the elements for array;15 13 18 6 17Minimum value in the given array is : 6

10. Write a program to find the sum of values of an array?A) //Program to find the Sum of a given array of elementsimport java.util.Scanner;class Sumaryele{public static void main(String args[]){int i, sum,n;int a[]=new int[10];System.out.println("Enter the size of the array: ");Scanner in=new Scanner(System.in);n=in.nextInt();System.out.println("Enter the elements for array: ");

Page 23: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

for(i=1;i<=n;i++){a[i]=in.nextInt();}sum=0;for(i=1; i<=n;i++){sum=sum+a[i]; }System.out.println("Sum of elements in the given array is: "+sum);}}Output:Enter the size of the array: 5Enter the elements for array: 12 10 23 15 25Sum of elements in the given array is: 85

11. Write a program for matrix addition?A) // Matrix Addition

import java.util.Scanner;

class AddTwoMatrix

{

public static void main(String args[])

{

int m, n, c, d;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");

m = in.nextInt();

n = in.nextInt();

int first[][] = new int[m][n];

int second[][] = new int[m][n];

Page 24: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

int sum[][] = new int[m][n];

System.out.println("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

first[c][d] = in.nextInt();

System.out.println("Enter the elements of second matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

second[c][d] = in.nextInt();

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

sum[c][d] = first[c][d]+ second[c][d];

System.out.println("First Matrix :-");

for ( c = 0 ; c < m ; c++ )

{

for ( d = 0 ; d < n ; d++ )

System.out.print(first[c][d]+"\t");

System.out.println();

}

System.out.println("Second Matrix:-");

for ( c = 0 ; c < m ; c++ )

{

Page 25: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

for ( d = 0 ; d < n ; d++ )

System.out.print(second[c][d]+"\t");

System.out.println();

}

System.out.println("Sum of entered matrices:-");

for ( c = 0 ; c < m ; c++ )

{

for ( d = 0 ; d < n ; d++ )

System.out.print(sum[c][d]+"\t");

System.out.println(); } } }

Output:

Enter the number of rows and columns of matrix

2

2

Enter the elements of first matrix

1 2

3 4

Enter the elements of second matrix

5 6

7 8

First Matrix :-

1 2

3 4

Page 26: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Second Matrix:-

5 6

7 8

Sum of entered matrices:-

6 8

10 12

12. Write a program for Matrix Multiplication?A) // Program for Multiplication of two matrices.import java.util.Scanner;class Mulmat{public static void main(String args[]){int m,n,i,j,k;Scanner in=new Scanner(System.in);System.out.println("Enter the number of rows and columns of matrix:");m=in.nextInt();n=in.nextInt();int a[][]=new int[m][n];int b[][]=new int[m][n];int c[][]=new int[m][n];System.out.println("Enter the elements of first matrix:");for(i=0;i<m;i++) for(j=0;j<n;j++) a[i][j]=in.nextInt();System.out.println("Enter the elements of b matrix:");for(i=0;i<m;i++) for(j=0;j<n;j++) b[i][j]=in.nextInt();for(i=0;i<m;i++){ for(j=0;j<n;j++){ c[i][j]=0; for(k=0;k<2;k++) { c[i][j]=c[i][j]+(a[i][k]*b[k][j]); // Multiplication of two matrices }}}for(i=0;i<m;i++){

Page 27: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

for(j=0;j<n;j++) System.out.print(c[i][j]+"\t"); System.out.println();}}}

Output:Enter the number of rows and columns of matrices 2 2Enter the elements of first matrix: 1 2 3 4Enter the elements of second matrix: 1 2 3 47 1015 22

UNIT – IVIMPLEMENTING OOPS IN JAVA

Long Answer questions:

1. What is polymorphism? Explain Polymorphism with an example?A) Polymorphism: Polymorphism means the ability to take more than one form is called Polymorphism.

We can store all the objects of extended classes in to variable of parent class. The only possible way to access an object is through a reference variable. A reference variable can be only one type. Once declared the type of reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Ex: class Box{int w,h;void info( ){System.out.println("This is a simple box");System.out.println("width = "+w+"height="+h);}}class woodenBox extends Box{int life;void info( ){System.out.println("This is a wooden box");}}class SteelBox extends Box{int wg;void info( ){System.out.println("This is a steel box");

Page 28: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

}}class LargewoodenBox extends woodenBox{void info( ){System.out.println("This is a Huge wooden Box");}}

class BoxDemo{public static void main(String ary[ ]){Box x;Box b1= new Box( );woodenBox wb=new woodenBox( );SteelBox s1=new SteelBox( );LargewoodenBox p1=new LargewoodenBox( );b1.info( );wb.info( );s1.info( );p1.info( );

}}

Output:This is a simpleboxWidth=0 hieght=0This is a wooden boxThis is a steel boxThis is a Huge wooden Box

2. What is Inheritance? Explain Inheritance with an example?A) Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. Inheritance provides the idea of reusability.

Through inheritance we can create new classes that are built upon existing Classes. When we inherit from an existing class, we can reuse methods and fields, and we add new methods and fields to adopt our new class to new situations.

Syntax:class<subclass_name> extends <superclass_name>{

//methods and fields}The keyword extends indicates that we are making a new class that derived from an existing

class. i.e., a class that is inherited is called superclass. The new class is called subclass.

Page 29: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Ex: class Employee{int salary=60000;

}class Programmer extends Employee{

int bonus= 10000;}class InterfaceExample{public static void main(String args[ ]){Programmer p=new Programmer( );System.out.println("Programmer salary is: " +p.salary);System.out.println("Programmer bonus is: " +p.bonus);}}Output:Programmer salary is: 60000Programmer bonus is: 10000

3. What is Method Overloading? Explain Method Overloading with an example?A) Method Overloading: Overloading means creating more than a single method with same name with different signatures.

Java identifies the methods with by comparing their signatures like return types, constructor parameters & access modifiers used.Ex: class Overload {

void test(int a){System.out.println("a:"+a); }

void test(int a, int b){System.out.println("a and b:"+a+","+b);}

double test(double a){System.out.println("double a" +a);return a*a; }}

class MethodOverloading{public static void main(String args[ ]){Overload overload=new Overload();double result;overload.test(10);overload.test(20,30);result=overload.test(2.5);System.out.println("Result:"+result);

Page 30: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

}}Output:

a: 10a and b: 20,30double a: 2.5Result: 6.25

UNIT – VPACKAGES AND INTERFACES

1. What is a package? Write the syntax to define a packageA) Package: Packages are a way of grouping a variety of classes and or interfaces together. The grouping is done according to their functionality. Packages are act like containers for classes.

Syntax: 1. To create a package:

package package_name;2. To import a package:

import package_name.*;

2. What is the difference between Java API Packages and User – Defined Packages?A) Java API Packages: Java API provides a large number of classes grouped into different packages according to functionality like lang, util, io, awt, net Etc., Each package provides different functionality to our java program.User – Defined Package: A package which is defined by a programmer which is not already existed in the Java API.

3. How can we import a package from other package?A) Java system package can be accessed either by using fully qualified class name (or) using short cut approach through the import statement. We use the import statement where there are many references to a particular package or the package name is too long.

import <package_name>.*;import x.* /* this statement make available all the classes existed in that package to the

current working program.*/

4. What is an interface? Write the syntax to define an interface?A) Interface: Interface is a kind of class that contains fields and methods which are final fields and Abstract methods. This means, interfaces does not specify any code to implement these methods and data fields contains only constants.

Defining an Interface: Syntax: interface interface_name {

Page 31: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Variable Declaration; Method Declaration;}

5. Write any 4 Java API packages?A)

Package Purposejava.lang It includes classes for primitive types, strings, math functions, threads and exceptions.java.util Language utility classes such as vectors, hash tables, random numbers, date etc.,java.applet Classes for creating and implementing applets.java.awt Includes classes for windows, buttons, list, menus and so on.java.io Input or output support classes.

Long Answer Questions:

1. Write the benefits or advantages of packages and interfaces?A) Benefits of packages (or) Benefits by organizing classes into Packages:

1. Provides reusability of the class by the other programs existing in the same package.2. In packages, classes can be unique compared with classes in other packages.3. Packages provide a way to “hide” classes thus preventing other programs or packages from

accessing classes that are meant for internal use only.4. Packages offers a way of separation between “Design” and “Coding” by designing classes and

decide their relationships first and implementing the java code needed for the methods next. Benefits or Advantages of Interfaces:1. The legal implementations for a class are defined in the interface.2. Java provides an alternate approach for multiple inheritance known as Interfaces to support

the multiple inheritance.3. A java class cannot be subclass of more than one super class but it can implement more than

one interface.

2. How can we add a class to a package?A) Procedure to add a class to a package:

1. Define the class and make it public.2. Place the package statement before the class definition.3. Store this class file in the package directory.4. Compile the class file. This will create the class file and place it in the package directory.5. A non public class to a package also follows the same procedure.

Page 32: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

6. When we import the package with .* all the classes existed in that package are automatically imported to our program.Ex: package x;

public class{ //Body of class Y}

In place of statement “package x;” if we place the statement like “package x.*;” all the classes existed in the ‘package x’ are available to the “class Y”.

3. Write about relative and absolute paths?A) Each path in a class path is either an absolute path or relative path. An absolute path in absolute path in Unix begins with a forward slash ( / ). The leading slash indicates that this path is starting from the root directory of the system. A relative path is one that does not start with a slash.

1. When a class is put into a package, its fully qualified name must be used.2. An import statement provides an alternate to a class’s fully qualified name.3. In order for a class to be located, its fully qualified name must have a tight relationship with

the directory structure in which it resides.4. A classpath can contain both relative and absolute paths.5. A absolute paths start with a / or \ .6. Only the final directory in a given path will be searched.

4. Write the difference between Package and Interface?A) Interfaces Vs Packages

A package is just a mechanism for grouping objects, it is very similar to grouping items within a folder or directory on a file system. A class is found with in a package, but this does not have an impact on the class behavior.

An Interface, however, is a.java file that is used (implemented) by another class to tell the outside world that it conforms to a certain specification.

Interfaces have more in common with abstract classes than they do with packages. An Interface, by definition, cannot have any implemented methods.

An abstract class can define some methods and leave some methods to implemented by a subclass.

A class can implement many interfaces, but can only extend one (abstract) class.

5. Write the procedure to create a package with multiple public classes?A) Creating a package with multiple public classes by considering the following statements

1. Finalize the name of the package first.2. Create a subdirectory with this name under the directory where main source files are stored. 3. Create classes that are to be placed in the package in separate source files and declare the

package statement as first line of source file.package package_name;

Switch to the subdirectory created earlier and compile each source file. When completed, the package would contain .class files of all the source files.

6. Write the procedure to create a Package in Java?A) Steps involved in creating our own package are:

Page 33: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

1) Declare the package at the beginning of a file using the form package <package_name>;

2) Define the class that is to be put in the package and declare it “public’.3) Create a subdirectory under the directory where the main source files are stored.4) Store the listing as the classname.java file in the subdirectory created.5) Compile the file. This creates “ .class “ file in the subdirectory.Note: The subdirectory name must match the package name exactly.

Example:

Package1 containing single class ClassA importing ClassA from package1

UNIT – VIEXCEPTION HANDLING

1. What is debugging?A) Debugging: The process of identifying and removing user committed errors from a program is called debugging.

2. What are compile time error?A) Compile Time errors: A compile-time error happens when the program is being compiled. Generally, Compile-time errors are syntax errors, and they are caught by the compiler.

3. What are run time errors?A) Run time errors: Run-time errors occur at run-time. Generally, the program compiles but does not run correctly. Example, insufficient memory to store something or inability of the microprocessor to execute some statement comes under run-time error.

4. What are logical errors?A) Logical Errors: The programmer might be using a wrong formula or the design of the program itself is wrong. Logical errors are not detected either by Java compiler or JVM. The programmer solely responsible for them.

5. What are three types of errors?

package package1;public class ClassA{ public void displayA( ) { System.out.println(“Class A”); }

}

import package1.ClassA;class PackageTest1{ public static void main(String args[ ]) { ClassA objectA = new ClassA();objectA.displayA( );}

}

Page 34: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

A) Errors in java are basically three types those are Compile Time errorsRun time errorsLogical errors

6. What is an Exception?A) Exception: An Exception is an event or a problem, which occurs or rises during the execution of a program. It is a runtime error thrown by a class or method reporting an error in the code.

7. What are different types of Exceptions?A) Exceptions are basically two types, those are:

Checked Exceptions. Unchecked Exceptions.

Long Answer Questions:

1. Write about three types of errors?A) Compile Time errors: A compile-time error happens when the program is being compiled. Generally, Compile-time errors are syntax errors, and they are caught by the compiler. Run time errors: Run-time errors occur at run-time. Generally, the program compiles but does not run correctly. Example, insufficient memory to store something or inability of the microprocessor to execute some statement comes under run-time error. Logical Errors: The programmer might be using a wrong formula or the design of the program itself is wrong. Logical errors are not detected either by Java compiler or JVM. The programmer solely responsible for them.

2. What are two exception types? Or Write about exception types?A) Exceptions are basically two types, those are:

A) Checked Exceptions.B) Unchecked Exceptions.

A) Checked Exceptions: The Exceptions that are checked at compilation time by the java compiler are called Checked Exceptions. These Exceptions should either handle them or throw them without handling them by the programmer. Following are common checked exceptions.

Class Not Found Exception. IOException EOF Exception FileNotFound Exception NoSuchMethod Exception

B) Unchecked Exceptions: The exceptions which are checked by the JVM are called unchecked exceptions. These exceptions and errors and can compile the program. The programmer see their effect only when he runs the program. Following are common unchecked exceptions.

ArithmeticException Illegal Argument Exception Number Format Exception Index Out Of Bound Exception

Page 35: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Array Index Out Of Bounds Exception String Index Out Of Bounds Exception Null Pointer Exception.

3. Explain exception handling in three steps? Or Write about try, catch, throw, throws and finally keywords?

A) When there is an exception, the user data may be corrupted. This should be tackled by the programmer by carefully designing the program by using the following three steps.Step 1(try ): The programmer should observe the statements in his program where there may be a possibility of exceptions. Such statements should be written inside a try block. A try block looks like as follows

try {statements;

}

Step 2 (catch): The programmer should write the catch block where he should display the exception details to the user. This helps the user to understand that there is some error in the program. Catch block looks like as follows:

catch(Exceptionclass ref) {statements;

}The Throwable class of printStackTrace() method fetches exception details from the exception details from the exception stack and displays them. The ‘Throwable’ class is the super class of all errors and exceptions in the java language.

Throw is used to force an exception by the programmer.

Step 3 (finally): The programmer should perform cleanup operations like closing the files and terminating the threads in the finally block. The statements inside the finally block are executed irrespective of whether there is an exception or not. The finally block looks like as follows.

finally {Statements;

}

4. Explain an example of exception handling in the case of division by zero?A) program for causing division by zeropublic class DivideException{public static void main(String args[]){try{ int a=100,b=4; System.out.println(a/b); int c=100,d=0; System.out.println(c/d);}catch(ArithmeticException e){ System.out.println(e); System.out.println("Don't give denominator value as zero for division");

Page 36: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

}}} If we run the above program we will get the output as follows

25java.lang.ArithmeticException: / by zeroDon't give denominator value as zero for division

5. Write about some Java’s built in exceptions?A)

Exception Description1. Arithmetic Exception Arithmetic error, such as divide – by – zero .2. Array Index Out Of Bounds Exception Array index is out – of – bounds.3. Null Pointer Exception Invalid use of a null reference.4. Number Format Exception Invalid conversion of a string to a numeric format.5. Security Exception Attempt to violate security.6. String Index Out Of Bounds Attempt to index outside the bounds of a string.7. Index Out Of Bounds Exception Some type of index is out – of – bounds. 8. Class Cast Exception Invalid Cast.9. Class Not Found Exception Class not found10. No Such Method Exception A requested method does not exist.

UNIT VIITHREADS

1. What is multitasking?A) Multitasking: It is an operating system concept in which multiple tasks are performed simultaneously.

2. What is a thread?A) Thread: A thread is a single line of execution with in a program. A thread is created either by subclassing the Thread class or implementing the runnable interface.

3. What is multithreading?A) Multithreading: Multithreading is a programming concept in which a program or a process is divided into two or more sub programs or threads that are executed at the same time in parallel. Multiple threads can run concurrently in a single program.

4. What is meant by lightweight threads?A) Lightweight threads: Threads in java are subprograms of a main application program and share the same space, they are known as lightweight threads or lightweight processes.

Long Answer Questions:

Page 37: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

1. Write the difference between multithreading and multitasking?A)

Multi threading Multi tasking1. It is a programming concept in which a

program or a process is divided into two or more sub programs or threads that are executed at the same time in parallel.

1. It is an operating system concept in which multiple tasks are performed simultaneously.

2. It supports execution of multiple parts of a single program simultaneously.

2. It supports execution of multiple programs simultaneously.

3. The processor has to switch between different parts or threads of a program.

3. The processor has to switch between different programs are processes.

4. It is highly efficient. 4. It is less efficient in comparison to multithreading.

5. A thread is the smallest unit in multithreading.

5. A program or process is the smallest unit in a multitasking environment.

6. It helps in developing efficient programs. 6. It helps in developing efficient operating systems.

7. It is cost – effective in case of context switching.

7. It is expensive in case of context switching.

2. Write a simple program by using threads? A) class A extends Thread{public void run(){for(int i=1;i<=5;++i) System.out.println("\tForm thread A: i="+i); System.out.println("Exit from A");}}class B extends Thread{public void run(){for(int i=1;i<=5;++i) System.out.println("\t Form thread B: i=" +i); System.out.println("Exit from B");}}

class ThreadTest{public static void main(String args[]){new A().start();new B().start();}}Output:

Form thread A: i=1Form thread A: i=2Form thread A: i=3 Form thread B: i=1Form thread A: i=4 Form thread B: i=2

Page 38: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Form thread A: i=5Exit from A

Form thread B: i=3 Form thread B: i=4 Form thread B: i=5

Exit from B

UNIT VIIIJAVA APPLET

1. What is an Applet?A) Applet: An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API.

2. What are the important statements in applet?A) Java.applet.Applet.

Java.awt.Graphics.Without those important statements, the java compiler would not recognize the classes Applet

and Graphics, which the applet class refers to.

3. What are the methods in applet? A)

1. Init 2. Start3. Stop4. Destroy5. Paint

Long Answer Questions:

1. What are the differences between an Applet and stand alone java application?A) Differences between an Applet and Stand alone Java Application:

1. An applet is a Java class that extends the java.applet.Applet class.2. A main() method is not invoked on an applet, and an applet class will not define main().3. Applets are designed to be embedded within an HTML page.4. When a user views an HTML page that contains an applet, the code for the applet is

downloaded to the user’s machine.5. A JVM is required to view an applet. 6. The JVM on the user’s machine create an instance of the applet class and invokes various

methods during the applet’s lifetime.7. Applets have strict security rules that are enforced by the Web browser. 8. Other class that the applet needs can be downloaded in a single Java Architecture (JAR) file.

2. Write about the basic methods of the Applet class? Or Write the life cycle of an Applet?A) Life Cycle of an applet: Four methods give us the framework on which we build an applet.

Page 39: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

3. init : This method is intended for whatever initialization is needed for our applet. It is called after the param tags inside the applet tag have been processed.

4. Start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.

5. Stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.

6. Destroy: This method is only called when the browser shuts down normally7. Paint: Invoked immediately after the start() method and also any time the applet needs to

repaint itself in the browser. The paint() method is actually inherited from the java awt.

3. Write the step wise procedure to create and run an applet?

Her we are giving step wise procedure to create and run an applet

First create a java program hellojava.java

import java.awt.*;

import java.applet.*;

public class hellojava extends Applet

{public void paint (Graphics g)

{

g.drawString("Welcome to Computer students",10,100);

}}

When this above program is error free , automatically it creates hellojava.class and then create an html tag hellojava.html as follows. The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes an applet:

<HTML>

<HEAD>

<TITLE>

Page 40: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

WELCOME TO JAVA APPLET>

</TITLE>

</HEAD>

<BODY>

<CENTER>

<H1> WELCOME TO THE WORLD OF APPLETS</H1>

</CENTER>

<BR>

<CENTER>

<APPLET CODE= hellojava.class

WIDTH=400

HEIGHT=200>

</APPLET></CENTER>

</BODY>

</HTML>

An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser.

If we use appletviewer

appletviewer hellojava.html causes to display as follows.

Page 41: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

If we use Internet Explorer or Mozilla , causes to display as follows

Page 42: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

UNIT IXTHE JAVA ABSTRACT WINDOWING TOOLKIT

1. What is AWT?A) AWT: AWT stands for Abstract Window Tool Kit. It is a portable GUI library among various operating systems for stand-alone applications.

2. What is an user interface?A) User Interface: The user interface is that part of a program that interacts with the user of the program. User interfaces take many forms. These forms range in complexity from simple command – line interfaces to the point – and – click graphical user interfaces provided by many modern applications.

3. What are different types of components in AWT?A) Component: A graphical user interface is built of graphical elements called components. Typical components in such items are Button, Canvas, Checkbox, Choice, Label, List, Scrollbars, TextArea and TextField.

4. What are different types of containers in AWT?A) The AWT provides four container classes those are:

a) Windowb) Framec) Dialogued) Panel

5. What is a window container in AWT?A) Window: A top – level display surface (a window). An instance of the Window class is not attached to nor embedded within another container. An instance of the Window class.

6. What is a Frame container in AWT?A) Frame: A top – level display surface (a window) with a border and title. An instance of the Frame class may have a menu bar. It is otherwise very much like an instance of the Window class.

7. What is a Dialogue container in AWT?A) Dialogue: A top – level display surface ( a window) with a border and title. An instance of the dialog class cannot exist without an associated instance of the Frame class.

8. What is a panel container in AWT?A) Panel: A generic container for holding components. An instance of the Panel class provides a container to which to add components.

Page 43: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

9. Write about nine types of components classes?A. The AWT provides nine basic non-container component classes from which a user interface may be constructed.

Class Instance

Button

This class creates a labeled button. The application can cause some action to happen when the button is pushed. This image depicts views of a "Quit" button.

Checkbox

A check box is a graphical component that can be in either an "on" (true) or "off" (false) state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on."This image depicts the check box

Choice

The Choice class presents a pop-up menu of choices. The current choice is displayed as the title of the menu.

After this choice menu has been added to a panel, it appears as follows in its normal state:

Label

A Label object is a component for placing text in a container. A label displays a single line of read-only text. The text can be changed by the application, but a user cannot edit it directly.

Scrollbar

The Scrollbar class embodies a scroll bar, a familiar user-interface object. A scroll bar provides a convenient means for allowing a user to select from a range of values.

TextField A TextField object is a text component that allows for the editing of a single

Page 44: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

line of text.

CanvasA Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.

List

The List component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items

TextArea A TextArea object is a multi-line region that displays text. It can be set to allow editing or to be read-only.

10. Write about types of containers?A) The AWT provides four container classes. They are class Window and its two sub types – class Frame and class Dialog. As well as the Panel class. In addition to that the Applet class is a container – it is a subtype of the Panel class and can therefore hold components. The AWT provides four container classes those are:

Page 45: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

e) Windowf) Frameg) Dialogueh) Panel

a) Window: A top – level display surface (a window). An instance of the Window class is not attached to nor embedded within another container. An instance of the Window class.

b) Frame: A top – level display surface (a window) with a border and title. An instance of the Frame class may have a menu bar. It is otherwise very much like an instance of the Window class.

c) Dialogue: A top – level display surface ( a window) with a border and title. An instance of the dialog class cannot exist without an associated instance of the Frame class.

d) Panel: A generic container for holding components. An instance of the Panel class provides a container to which to add components.

11. Write about hierarchical order of AWT components?A)

12. Write a program for creating a frame by using AWT?A.

/* Create Frame by using AWT */

Menu Bar

ObjectJava.lang

Color

Font

Graphics

Menu component

Component

Border Layout

Grid Layout

Event

Button

Label

Canvas

Container

Scroll Bar

Text Component

Menu Item

Window

Pane

Text Field

Text Area

CheckBox Menu item

Menu

Layout manager

Frame

Dialog

Applet

File Dialog

Page 46: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

import java.awt.Frame; /* * To create a stand alone window, class should be extended from * Frame and not from Applet class. */public class CreateFrameWindowExample extends Frame{ CreateFrameWindowExample(String title){ //call the superclass constructor super(); //set window title using setTitle method this.setTitle(title); /* * Newly created window will not be displayed until we call * setVisible(true). */ this.setVisible(true); } public static void main(String args[]){ CreateFrameWindowExample window = new CreateFrameWindowExample("Create Window Example"); /*after display output window , you will have */ /* to terminate the program (by pressing ctrl+C) to close the frame window.*/ }}

13. Write a program for adding a component to a frame by using AWT?A. /*adding a component to a frame by using AWT*/

import java.awt.BorderLayout;

import java.awt.Component;

import java.awt.Frame;

import java.awt.TextArea;

public class CreateFrameExample {

Page 47: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

public static void main(String[] args) { // Create frame with specific title

Frame frame = new Frame("Example Frame");

// Create a component to add to the frame; in this case a text area with sample text

Component textArea = new TextArea("II year CSE syllabus is ...");

// Add the components to the frame; by default, the frame has a border layout

frame.add(textArea, BorderLayout.NORTH);

// Show the frame

int width = 300;

int height = 300;

frame.setSize(width, height);

frame.setVisible(true); }}

14. Write a program for adding two numbers by using AWT?A. The following program explains adding two numbers by using AWT

import java.awt.*;

import java.awt.event.*;

class ex1 extends Frame implements ActionListener {

Label l1,l2,l3,l4;

TextField t1,t2;

Button b1,b2;

ex1()

{ super("Addition of two numbers");

Page 48: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

setLayout(null);

setSize(500,400);

setVisible(true);

l1=new Label("Enter the first no:");

l2=new Label("Enter the second no:");

l3=new Label("The sum is:");

l4=new Label(null);

t1=new TextField();

t2=new TextField();

b1=new Button("ADD");

b2=new Button("Clear");

l1.setBounds(100,50,120,20);

add(l1);

t1.setBounds(240,50,50,20);

add(t1);

l2.setBounds(100,80,130,20);

add(l2);

t2.setBounds(240,80,50,20);

add(t2);

l3.setBounds(100,110,100,20);

add(l3);

l4.setBounds(210,110,60,20);

add(l4);

b1.setBounds(200,150,50,20);

add(b1);

Page 49: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

b2.setBounds(270,150,50,20);

add(b2);

b1.addActionListener(this);

b2.addActionListener(this);

addWindowListener( new WindowAdapter() {

public void windowClosing(WindowEvent we)

{ System.exit(0); } }); }

public void actionPerformed(ActionEvent ae)

{ float a,b,c;

if(ae.getSource()==b1)

{ a=Float.parseFloat(t1.getText().trim());

b=Float.parseFloat(t2.getText().trim());

c=a+b;

l4.setText(Float.toString(c)); }

else {

t1.setText(null);

t2.setText(null);

l4.setText(null); } }

public static void main(String s[])

{

ex1 ob=new ex1(); }}

Page 50: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

UNIT XEVENT HANDLING

1. What is an event?A) Event: Changing the state of on object is called an Event. Ex:click on button, dragging mouse etc.

2. What are steps to perform event handling?A) Following steps are required to perform event handling:

1. Implement the Listener Interface and overrides its methods.2. Register the component with the listener.

Long Answer Questions:

1. Write about four types of classes involved in event handling?A) Event handling involves four types of classes

1. Event Sources2. Event classes3. Event Listeners 4. Event Adapters

1. Event Sources: Event sources are components, subclasses of AWT components, capable to generate events. The event source can be a button, a frame or any other component.2. Event classes: Every event source generates an event and is named by some Java class. All events listed in java.awt.event package.3. Event Listeners: Listener is an Interface. The events generated by the GUI components are handled by a special group of classes known a “listeners”. Listeners are from java.awt.event package.4. Event Adapters: Adapters are abstract classes defined in java.awt.event package. Every listener that has more than one abstract method has got a corresponding adapter class. The adapters classes are used by the designers to avoid the heavy coding.

2. Write about Event classes and Listener Interfaces?A)

EventClasses Listener InterfacesAction event Action ListenerMouse Event Mouse listener and Mouse Motion ListenerMouse Wheel event Mouse Wheel ListenerKey Event Key ListenerItem Event Item Listener

Page 51: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Text Event Text ListenerAdjustment Event Adjustment ListenerWindow Event Window ListenerComponent Event Component ListenerContainer Event Container ListenerFocus Event Focus Listener

3. What are commonly used methods in Event Handling?A) For registering component with the listener, many classes provide the registration methods.

1. Button: Public void addActionListener(ActionListener a) {}2. MenuItem: Public void addActionListener(ActionListener a) {}3. Text Field: Public void addActionListener(ActionListener a) {}

Public void addTextListener(TextListener a) {}4. Text Area: Public void addTextListener(TextListener a) {}5. Check Box: Public void addItemListener(ItemListener a) {}6. Choice: Public void addItemListener(ItemListener a) {}7. List: Public void addActionListener(ActionListener a) {}

4.Write a program to display a text message “welcome” when we press mouse click

//displays a text message “welcome” when we press mouse clickimport java.awt.*;import java.awt.event.*;class AEvent extends Frame implements ActionListener{TextField tf;AEvent(){tf = new TextField();tf.setBounds(60,50,170,20);Button b = new Button("click me");b.setBounds(100,120,80,30);b.addActionListener(this);add(b);add(tf);setSize(300,300);setLayout(null);setVisible(true);}public void actionPerformed(ActionEvent e){tf.setText("welcome");}public static void main(String args[]){new AEvent(); } }

EXPANSIONS

Page 52: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

OOPS : Object Oriented Programming System Java API : Java Application programming InterfaceJVM : Java Virtual Machine.JRE : Java Run – Time Environment.JIT : Just in Time Compiler.JDB : Java debuggerAWT : Abstract Window ToolkitWORA : Write Once, Run Anywhere.

OOPS & JAVA

Model Paper-1

COMPUTER SCIENCE & ENGG- 2ND YEAR

PAPER-1: OOPS and JAVA

Time:- 3 Hrs Max. Marks:- 50

SECTION-A

Note:- 1. Answer ALL Questions: 10 x 2=20

2. Each Question carries 2 Marks.

1.Mention the access specifiers in Java.

1A. In java we have four Access Specifiers.

1. public2. private3. protected4. default(no specifier).

2. Define a constructor.

2A. A constructor initializes an object when it is created. It has the same name as its class and is

syntactically similar to a method. However, constructors have no explicit return type.

3. Define an Array.

Page 53: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

3A. Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type.

A[0] = 12

A[1] = -5

A[2] = 18

A[3] = 2

A[4] = 16

In the above A is the array name ,0,1,2,3 and 4 are indexes , 12, -5,18,2,and 16 are data elements. Array A containing 5 integer type elements.

4. Define Polymorphism.

4A. Generally, the ability to appear in many forms. In OOPS, polymorphism refers to a programming

language’s ability to process objects differently depending on their data type or class. More

specifically, it is the ability to redefine methods for derived classes.

5. Define an interface.

5A. Interface: Interface is a kind of class that contains fields and methods which are final fields and Abstract methods. This means, interfaces does not specify any code to implement these methods and data fields contains only constants.

Defining an Interface:

Syntax: interface interface_name {

Variable Declaration;

Method Declaration;

}

6. Mention the names of any two Exception Handling Methods.

6A. try()

Page 54: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

catch()

finally()

7. Define a thread.

7A.  Thread: A thread is a single line of execution with in a program. A thread is created either by subclassing the Thread class or implementing the runnable interface.

8. Define an Applet.

8A. An applet is a Java program that runs in a Web browser.

9. Expand the term AWT.

9A.AWT: Abstract Window Tookit.

10. Mention any two button events.

10A. ActionEvent , FocusEvent.

SECTION – B 5 x 6 = 30

Note:- 1. Answer ANY FIVE Questions:

2. Each Question carries 6 Marks.

11. Describe the main features of OOPS.

11A. There are four main features of OOPS are

Abstraction Encapsulation Polymorphism Inheritance

Abstraction: The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface).

 Encapsulation: The process of wrapping data into a single unit is called Encapsulation.

Page 55: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Inheritance: This is the process in which a properties of a predefined class can be inherited in a new class making the object of that class in the making class.

Polymorphism: This is the process in which a program can have more than one function with the same name but different parameters.

12. Describe the main data types in Java?

12A. Java has four main primitive data types built into the language. We can also create our own data types.

Integer: byte, short, int, and long.

Floating Point: float and double

Character: char

Boolean: variable with a value of true or false.

The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.

Data Type Default Value (for fields) Range

Byte 0 -127 to +128

Short 0 -32768 to +32767

Int 0

Long 0L

Float 0.0f

Double 0.0d

Char ‘\u0000′ 0 to 65535

String (object) Null

Boolean False

Page 56: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

13. Create a method that adds two integers supplied to it and returns the sum to the calling object.

13A.

// finds sum of two integers by a method.import java.util.Scanner;public class sum1{ /** Main method */ public static void main(String[] args) {

Scanner in = new Scanner(System.in);System.out.println("enter first value");

int i = in.nextInt();System.out.println("enter second value");

int j = in.nextInt(); int k = sum(i, j); System.out.println("The sum of " + i + " and " + j + " is " + k); } /** Return the sum of two numbers */ public static int sum(int num1, int num2) { int result; result = num1 + num2 ;

return result; }}

Input:enter first value 5enter second value 3

output:The sum of 5 and 3 is 8

14. Describe the Switch statement in Java with an example.

14A. The switch Statement:

A switch statement is used instead of multiple if statements. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Page 57: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Syntax:

The syntax of switch statement is

switch(expression){

case value :

//Statements

break; //optional

case value :

//Statements

break; //optional

//You can have any number of case statements.

.

.

default : //Optional

//Statements

}

// program displays color red for r ,blue for b , green for g // and black for any other character by using switch statementimport java.util.Scanner;public class test6 { public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("enter a color code"); String color = in.next();

switch(color) { case "r" : System.out.println("Red"); break; case "b" :

Page 58: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

System.out.println("Blue"); break; case "g" : System.out.println("Green"); break; default : System.out.println("Black"); } }}

Input:enter a color code routput:Red

Input:enter a color code boutput:Blue

Input:enter a color code koutput:Black

15. Describe the use of break and continue statements with an example each.

15A.  break :

The break keyword is used exit from a loop. The break keyword must be used inside any loop or a switch statement.

The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:

The syntax of a break is a single statement inside any loop:

break;

Example:

public class Test {

Page 59: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

public static void main(String args[]){

int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){

if( x == 30 ){

break;

}

System.out.println( x );

}

}

}

This would produce following result:

10

20

continue :

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:

The syntax of a continue is a single statement inside any loop:

continue;

Example:

public class Test {

Page 60: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

public static void main(String args[]){

int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){

if( x == 30 ){

continue;

}

System.out.print( x );

System.out.print("\n");

}

}

}

This would produce following result:

10

20

40

50

16. Explain Inheritance with an example?

16A.  Inheritance

Inheritance is a mechanism in which one object acquires all the properties and behaviors

of parent object.

Syntax of inheritance

class <subclass-name> extends <superclass-name>

{

// methods and fields

}

Page 61: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

The keyword extends indicates that you are making a new class that derives from an existing class. In the terminology of java , a class that is inherited is called a superclass. The new class is called a subclass.

As displayed in the above figure , Programmer is the subclass and Employee is the superclass. Relationship between two classes id programmer IS-A employee. It means programmer is a type of employee.

The below program InheritanceExample.java shows that how the values are displaying through inheritance.

class Employee{

int salary = 60000; }

class Programmer extends Employee{

int bonus = 10000;}

class InheritanceExample{

public static void main(String args[])

{

Programmer p = new Programmer();

System.out.println("programmer salary is:" +p.salary);

System.out.println("programmer bonus is:" +p.bonus);

Employee

Programmer

Page 62: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Output of the above program is

programmer salary is:60000

programmer bonus is:10000

17. Explain Packages in Java with an example.

17A. Package: Packages are a way of grouping a variety of classes and or interfaces together. The grouping is done according to their functionality. Packages are act like containers for classes.

 Java packages are classified into two types.  They are:

1. Java API Packages.

2. User – Defined Packages.

Syntax:

1. To create a package:

package package_name;

2. To import a package:

import package_name.*;

Java API Packages: Java API provides a large number of classes grouped into different packages according to functionality like lang, util, io, awt, net Etc., Each package provides different functionality to our java program.

Page 63: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

User – Defined Package: A package which is defined by a programmer which is not already existed in the Java API.

Example:

Package1 containing single class Cla importing ClassA from package1

18. Describe about any two methods of an Applet Class.

18A.

1. init(): The applet's starts here. In this method, the applet object is created by the browser. Because this method is called before all the other methods, programmer can utilize this method to instantiate objects, initialize variables, setting background and foreground colors in GUI etc.; the place of a constructor in an application. It is equivalent to born state of a thread.

2. start(): In init() method, even through applet object is created, it is in inactive state. An inactive applet is not eligible for microprocessor time even though the microprocessor is idle. To make the applet active, the init() method calls start() method. In start() method, applet becomes active and thereby eligible for processor time.

Model Paper-II

COMPUTER SCIENCE & ENGG- 2ND YEAR

PAPER-1: OOPS and JAVA

Time:- 3 Hrs Max. Marks:- 50

SECTION-A

Note:- 1. Answer ALL Questions:

package package1;

public class ClassA

{

public void displayA( )

{

import package1.ClassA;

class PackageTest1

{

public static void main(String args[ ])

{

Page 64: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

2. Each Question carries 2 Marks. 10 x 2=20

1. Who developed java language and in which enterprise?

1A. Java was developed by James Gosling at Sun Microsystems in 1995.

2. What are four main primitive data types in Java?2A. The Four Primitive Data Types in JAVA are:

Integer: byte, short, int, and long. Floating Point: float and double Character: char Boolean: variable with a value of true or false.

3. What are various loop statements?

3A. There are three loop statements in java

while do...while for

4. What is method of overloading?

4A. Overloading means creating more than a single method with same name with different signatures.5. What is a package?

5A. Package is basically a collection of predefined or ready-made classes that can be used in your java

program to make shorter as well as easier

6. What are three types of errors?

6A. There are three types of errors

1. compile time errors2. run time errors3. logical errors.

7. What is multitasking?

7A. Multitasking allows the user to activate and accomplish more than one task at a time. For

Page 65: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

example, working on a document file in ms-word , playing mp3 and copying a files etc.,

8. What is an applet?

8A. An applet is a Java program that runs in a Web browser.

9. What is an AWT?

9A. AWT stands for Abstract Window ToolKit. It is a portable GUI library among various

operating systems for stand-alone applications.

10. What is an event?

10A. Changing the state of an object is known as an event.

For example , click on a button, dragging a mouse etc.

SECTION – B

Note:- 1. Answer ANY FIVE Questions:

2. Each Question carries 6 Marks. 5 x 6 = 30

11. Write about the main features of java.

11A. Main Features of java

Object Oriented : In java everything is an Object. Java can be easily extended since it is based on the Object model.

Platform independent: Java programs can be run on any operating system. Simple :Java is designed to be easy to learn. Secure : With Java's secure feature it enables to develop virus-free, tamper-free systems. Architectural- neutral :Java compiler generates an architecture-neutral object file format

which makes the compiled code to be executable on many processors, with the presence of Java runtime system.

Portable : We may carry the java bytecode to any platform. robust Robust : Java compels the programmer to be thorough. It carries out type checking at both

compile and runtime making sure that every data structure has been clearly defined and typed.

Page 66: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Multi-threaded : With Java's multi-threaded feature it is possible to write programs that can do many tasks simultaneously.

Interpreted :Java byte code is translated on the fly to native machine instructions and is not stored anywhere.

High Performance: With the use of Just-In-Time compilers Java enables high performance. Distributed :Java is designed for the distributed environment of the internet. Dynamic : Java is considered to be more dynamic than C or C++ .

12. Explain the Arithmetic operators with examples.

12A. The Arithmetic Operators:

Arithmetic operators are listed below.

Operator Purpose

+ Addition

- Subtraction

* Multiplication

/ Division

% Remainder after integer division

a)Integer  arithmetic:

Suppose a and b are integer variables and assigned a =5 and b = 3 then:

Operator Arithmetic Expression Result

+ a+b 8

- a-b 2

* a*b 15

/ a/b 1

% a%b 2

b) Real  arithmetic:

unlike C , java allows modulus operator to the float values. It returns float value after integer division.

Here quotient must be integer value.

Page 67: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

Suppose x and y are float variables and assigned x =20.5 and y = 10.5 then:

Operator Arithmetic Expression Result

+ x+y 31.0

- x-y 10.0

* x*y 215.25

/ x/y 1.9523809523809523

% x%y 10.0

c) Mixed mode

When one of operands is real and the other is integer , the expression is called mixed-mode arithmetic expression.

In an arithmetic expression all float operands must be converted as integer operands then the result will be in integer mode.

Example:

(int) 12.0/5 gives result 2. Here 12.0 is float operand , 5 is an integer operand . In the expression 12.0 converted into integer type as 12 and then divided by integer 5 gives result integer 2.

In an arithmetic expression all integer operands must be converted as float operands then the result will be in float mode.

Example:

12.0/(float) 5 gives result 2.4 Here 12.0 is float operand , 5 is an integer operand. In the expression 5 is converted into float type as 5.0 and then 12.0 is divided by float 5 gives result integer 2.4

13. Explain the Relational operators with examples.

13A. The Relational Operators:

There are six following relational operators supported by Java language

Operator Purpose

== is Equal to

!= is Not equal to

Page 68: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

> is Greater than

< is Less than

>= is Greater than or equal to

<= is Less than or equal to

Suppose a , b and c are integer variables and assigned 3,5and 10 respectively.

Relational  Expression Result

a>b False

(a+b) < c True

a>=3 True

a != b True

b <= a False

c == 10 True

14. Write about if and if..else statements.

14A.

a) The if Statement:

An if statement consists of a Boolean expression followed by one or more statements.

Syntax:

The syntax of an if statement is:

if(Boolean_expression)

{

Page 69: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

//Statements will execute if the Boolean expression is true

}

If the boolean expression evaluates to true then the block of code inside the if statement will be executed. If it is false simply bypass the block of code.

Ex: if (a>b) big = a;

b)The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax:

If Boolean expression is true then the expr1 is executed. If Boolean expression is false expr2 is executed.

Ex; if (a>b) big= a; else big = b;

15. Write a program to find factorial of a given number.

15A. 

// finds factorial by using while loop

import java.util.Scanner;

class factorialw

{public static void main(String Args[])

{

int i,f=1,n;

System.out.println("enter an integer");

Scanner in = new Scanner(System.in);

n = in.nextInt();

i=1;

If (Boolean expression) expr1; else expr2;

Page 70: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

while(i<=n){

f*=i;++i;}

System.out.println("factorial of " +n+ " is " +f);

}}

Input:

enter an integer 5

output:

factorial of 5 is 120

16. Explain the polymorphism with an example.

16A.

Polymorphism:Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

The following BoxDemo.java program explains polymorphism

class Box {

int w,h;

void info() {

System.out.println("This is a simple box");

System.out.println("width = "+ w + " hieght "+ h);

} }

class woodenBox extends Box {

int life;

void info( ){

System.out.println("This is a wooden box"); }

}

class SteelBox extends Box {

int wg;

void info( ) {

System.out.println("This is a steel box"); }

}

class LargewoodenBox extends woodenBox {

void info() {

System.out.println("This is a Huge wooden box"); }

}

class BoxDemo {

public static void main ( String ary[ ] ) {

Box x;

Box b1 =new Box( );

woodenBox wb=new woodenBox( );

SteelBox s1=new SteelBox( );

Page 71: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

The output of the above program

This is a simple boxwidth = 0 hieght 0This is a wooden boxThis is a steel boxThis is a Huge wooden box

17. Write about relative and absolute paths.

17A.   Relative and Absolute Paths

A class path is a collection of one or more paths. Each path in a class path is either an absolute path or relative path. An absolute path in absolute path in Unix begins with a forward slash (/) . The leading slash indicates that this path is starting from the root directory of the system. Because it’s starting from the root, it doesn’t matter what the current directory is – a directory’s absolute path is always the same. A relative path is one that does not start with a slash.

Page 72: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems

When a class is put into a package, its fully qualified name must be used. An import statement provides an alternate to a class’s fully qualified name. In order for a class to be located, its fully qualified name must have a tight relationship with the

directory structure in which it resides. A classpath can contain both relative and absolute paths An absolute path starts with a / or \. Only the final directory in a given path will be searched.

18. Write about the life cycle of an Applet .

18A. There are 5 states of an Applet from the state of object creation to object removal. These states are called methods or life cycle of an Applet. The 5 methods are

3. init(): The applet's starts here. In this method, the applet object is created by the browser. Because this method is called before all the other methods, programmer can utilize this method to instantiate objects, initialize variables, setting background and foreground colors in GUI etc.; the place of a constructor in an application. It is equivalent to born state of a thread.

4. start(): In init() method, even through applet object is created, it is in inactive state. An inactive applet is not eligible for microprocessor time even though the microprocessor is idle. To make the applet active, the init() method calls start() method. In start() method, applet becomes active and thereby eligible for processor time.

5. paint(): This method takes a java.awt.Graphics object as parameter. This class includes many methods of drawing necessary to draw on the applet window. This is the place where the programmer can write his code of what he expects from applet like animation etc. This is equivalent to runnable state of thread.

6. stop(): In this method the applet becomes temporarily inactive. An applet can come any number of times into this method in its life cycle and can go back to the active state (paint() method) whenever would like. It is the best place to have cleanup code. It is equivalent to the blocked state of the thread.

7. destroy(): This method is called just before an applet object is garbage collected. This is the end of the life cycle of applet. It is the best place to have cleanup code. It is equivalent to the dead state of the thread.

***

Page 73: csevoc.webnode.com …  · Web viewUNIT - I. OBJECT-ORIENTED PROGRAMMING AND JAVA. Who developed Java language? A) Java was developed by . James Gosling . at . Sun Microsystems