Sie sind auf Seite 1von 32

1

PRIYADARSHINI ENGINEERING COLLEGE – VANIYAMBADI


(Approved by AICTE, New Delhi, Affiliated to Anna University-Chennai)
Listed in 2(f) & 12(B) Sections of UGC

DEPARTMENT OF COMPUTER APPLICATIONS


III SEMESTER
MC5304-PROGRAMMING WITH JAVA
REGULATION 2017

UNIT I
JAVA FUNDAMENTALS

1. Who is the founder of JAVA?


 James Gosling - Sun Microsystems
 Co founder – Vinod Khosla
 Oak - Java, May 20, 1995, Sun World

2. Describe JDK Evolutions


 JDK 1.0 (January 23, 1996)
 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
 Java SE 6 (December 11, 2006)
 Java SE 7 (July 28, 2011)

3. Compare the features of JAVA AND C:


 Java is a lot like C but the major difference between Java and C is that Java is an
object-oriented language and mechanism to define classes and objects.
 Java does not include the C unique statement keywords goto, sizeof, and typedef.
 Java does not contain the data types struct, union and enum.
 Java does not define the type modifiers keywords auto, extern, register, signed
and unsigned.
 Java does not support an explicit pointer type.
 Java does not have a preprocessor and therefore we cannot use # define, #include,
and # ifdef statements.
 Java does not support any mechanism for defining variable arguments to
functions.
 Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
 Java add new operators such as instanceof and >>>.
 Java adds labelled break and continue statements.
 Java adds many features required for object-oriented programming.

MC5304-programming with java 5119/PEC/MCA


2

4. Compare the features of JAVA AND C++:


 Java is a true object-oriented language while C++ is basically C with object-
oriented extension.
 Listed below are some major c++ features that were intentionally committed from
Java or significantly modified.
 Java does not support operator overloading.
 Java does not have temple classes as in C++.
 Java does not support multiple inheritence of classes. This is accomplished using
a new feature called "interface".
 Java does not support global variables. Every variable and
method is declared within a class and forms parts of that class.
 Java does not use pointers.
 Java has replaced the destructors function with a finalize()
function.
 There are no header files in Java.

5. List out JAVA EDITIONS.


 J2SE(Java 2 Standard Edition) - to develop client-side standalone applications or
applets.
 J2ME(Java 2 Micro Edition ) - to develop applications for mobile devices such as
cell phones.
 J2EE(Java 2 Enterprise Edition ) - to develop server-side applications such as
Java servlets and Java ServerPages.

6. List the features of java applications


Sun Micro Systems officially describes Java with the following features
 Compiled and Interpreted
 Platform Independent and Portable
 Object Oriented
 Robust and Secure
 Distributed
 Simple, Small and Familiar
 Multithreaded and Interactive
 High Performance
 Dynamic and Extensible

7. Define API.
Java environment includes a large number of development tools and hundreds of classes
and methods. The development tools are part of the system known as Java Development
Kit (JDK) and the classes and methods are parts of the Java Standard Library (JSL), also
known as the Application Programming Interface (API).

8. Define Java Developing Kit


The Java Developing Kit comes with a collection of tools that are used for developing
and running Java programs. They includes:

Table 2.3 list these tools and their descriptions.

MC5304-programming with java 5119/PEC/MCA


3

9. How will you build and run Java Program?


 To create a Java program, we need to create a source code file using a text editor.
 The source code is then compiled using the Java compiler Javac and executed
using the Java interpreter Java.
 The Java debugger jdk is used to find errors, if any, in the source code.
 A compiled Java program can be converted into a source code with the help of
Java disassembler Javap.

MC5304-programming with java 5119/PEC/MCA


4

10. List the different types of packages


 Language Support Package: A collection of classes and methods required for
implementing basic features of Java.
 Utilities Packages: A collection of classes to provide utility functions such as
date and time functions.
 Input/Out Package: A collection of classes required for input/ output
manipulation.
 Networking Package: A collection of classes for communicating with other
computers via Internet.
 AWT Package: The Abstract Window Tools Kit packages contains classes that
implements platform-independent graphical user interface.
 Applet Package: This includes a set of classes that allows us to create Java
applets.

11. What is Java Standard Library (JSL)?


 A class library is a collection of classes that we can use when developing
programs
 The Java standard class library is pad of any Java development environment
 Its classes are not pad of the Java language perse, but we rely on them heavily
 Various classes we've already used (system, Scanner, string) are pad of the Java
standard class Library (Look them up on Sun website)
 Other class libraries can be obtained through third party vendors

12. Define expressions


An expression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language, that evaluates to a single
value. You've already seen examples of expressions, illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
System.out.println("value1 == value2");

13. List out the Java Operators.


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators

14. Define and List the Relational Operators:


Java has six relational operators that compare two numbers and return a boolean value.
The relational operators are < , > , <= , >= , == , and != . True if x is less than y,
otherwise false. True if x is greater than y, otherwise false.
A relational operator compares two values and determines the relationship between them

MC5304-programming with java 5119/PEC/MCA


5

15. What are Arithmetic Operators?


The arithmetic operators are used to construct mathematical expressions as in algebra.
Their operands are of numeric type.

Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement

.
16. Define Bitwise Operators with example
Bitwise operators is used to control values of primitive data-types such as long, integer,
short and byte. These operators do changes to the variables by doing some action and
manipulation on bits level. There are four defined bitwise operators in java which are :
AND operator, OR operator, XOR operator and complement operator. The first three
operators are binary which means that they need two operands while the last one is unary
operator which means it needs only one operand. Next will explain the usage of each
operator by example.
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}

MC5304-programming with java 5119/PEC/MCA


6

}
17. Define logical operator
A logical operator (sometimes called a “Boolean operator”) in Java programming is an
operator that returns a Boolean result that’s based on the Boolean result of one or two
other expressions.
Sometimes, expressions that use logical operators are called “compound expressions”
because the effect of the logical operators is to let you combine two or more condition
tests into a single expression.

18. Mention the usage of Conditional AND and OR


Conditional AND: if the operand on the left returns false, it returns false without
evaluating the operand on the right.
Conditional OR: if the operand on the left returns true, it returns true without evaluating
the operand on the right.

19. Define Assignment Operator


The assignment operator (=) is the most commonly used binary operator in Java. It
evaluates the operand on the tight hand side and then assigns the resulting value to a
variable on the left hand side. The right operand can be a variable, constant, function call
or expression. The type of right operand must be type compatible with the left operand.
The general form of representing assignment operator is x=y.

Operator Usage Effect


+= a+=b; a=a+b;
-= a-=b; a=a-b;
*= a*=b; a=a*b;
/= a/=b; a=a/b;
%= a%=b; a=a%b;
&= a&=b; a=a&b;
|= a|=b; a=a|b;
^= a^=b; a=a^b;
<<= a<<=b; a=a<<b;
>>= a>>=b; a=a>>b;
>>>= a>>>=b; a=a>>>b;

20. Define Instanceof Operator

The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).The instanceof in java is also known as type
comparison operator because it compares the instance with type. It returns either true or
false. If we apply the instanceof operator with any variable that has null value, it returns
false.

Example:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}

MC5304-programming with java 5119/PEC/MCA


7

}
21. Define and list CONTROL STRUCTURE
A control structure is a block of programming that analyzes variables and chooses a
direction in which to go based on given parameters. The term flow control details the
direction the program takes (which way program control "flows")

In Java, control statements can be divided into the following three categories:
 Selection Statements
 Iteration Statements
 Jump Statements

22. List the SELECTION STATEMENTS


Selection statements allow you to control the flow of program execution on the basis of
the outcome of an expression or state of a variable known during runtime.
Selection statements can be divided into the following categories:
 The if and if-else statements
 The if-else statements
 The if-else-if statements
 The switch statements

23. Define The if statements with example


The first contained statement (that can be a block) of an if statement only executes when
the specified condition is true. If the condition is false and there is not else keyword then
the first contained statement will be skipped and execution continues with the rest of the
program. The condition is an expression that returns a boolean value.
Example
import java.util.Scanner;
class IfDemo
{
public static void main(String[] args) {
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter Age: ");
age = inputDevice.nextInt();
if(age > 18)
System.out.println("above 18 ");
}
}

24. State the need of if-else statements :

In if-else statements, if the specified condition in the if statement is false, then the
statement after the else keyword (that can be a block) will execute.
import java.util.Scanner;
public class IfElseDemo
{
public static void main( String[] args )
MC5304-programming with java 5119/PEC/MCA
8

{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 )
System.out.println( "above 18 " );
else
System.out.println( "below 18" );
}
}

25. State the need of The if-else-if statements :


This statement following the else keyword can be another if or if-else statement.
That would looks like this:

if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;

Whenever the condition is true, the associated statement will be executed and the
remaining conditions will be bypassed. If none of the conditions are true then the else
block will execute.

import java.util.Scanner;
public class IfElseIfDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "not matched" );
}
}

26. Give the syntax of The Switch Statements :


The switch statement is a multi-way branch statement. The switch statement of Java is
another selection statement that defines multiple paths of execution of a program. It
provides a better alternative than a large series of if-else-if statements.

MC5304-programming with java 5119/PEC/MCA


9

Syntax of switch-case:

switch(expression){
case 1 :
action1 statement;
break;
case 2:
action2 statement;
break;
.
.
.
case N:
actionN statement;
break;
default:
default statement;
}

27. List out the iteration statements

Repeating the same code fragment several times until a specified condition is satisfied is called
iteration. Iteration statements execute the same set of instructions until a termination condition is
met.

Java provides the following loop for iteration statements:

 The while loop


 The do-while loop
 The for loop

28. Give the syntax of The while loop

It continually executes a statement (that is usually be a block) while a condition is true. The
condition must return a boolean value.

Syntax of while loop:

while (condition) {
action statements:
}
Where condition: is any boolean expression that returns a true or false value. The loop
continues upto condition returns true value.

Example :

int i = 1;
while(i<=5){
i++;
System.out.println(“value of i is : “+i);

MC5304-programming with java 5119/PEC/MCA


10

29. Give the syntax of do-while loop

The do-while loops execute certain statements till the specified condition is true. This
loop ensures that the loop body is executed atleast once.
Syntax of do-while loop:
do{
action statements;
}while(condition){
action statements;
}
Example :

int j = 8;
do{
j = j+2;
System.out.println(“value of j is : “ +j);
}while(j>=10 && j<=50){
j = j+5;
System.out.println(“value of j is : “ +j);
}

30. Define for loop with example

All loops have some common feature: a counter variable that is initialized before the loop
begins. The for loop provides the feature that, initialized the variable before loop begins,
a condition for counter variable and counter upto which loop lasts.

Syntax of for loop:

for(initialization statements; condition; increment/decrement statements){


action statements;
.
.
}
where initialization statements : sets or initialize the value for counter variable.
condition : A boolean expression that returns true or false value. The loop terminates if
false value is returned. Increment/decrement statements : Modifies the counter
variable. This statements are always executed after the action statements, and before the
subsequent condition check.

Example :

for(int i=1;i<=10;i++){
System.out.println(“Value of i is “ +i);
}

MC5304-programming with java 5119/PEC/MCA


11

31. List out the jump statements


Jump statements are used to unconditionally transfer the program control to another part of the
program.
Java provides the following jump statements:

 break statement
 continue statement
 return statement

32. Differentiate Break Statement & Continue statement:


The break statements are used to,
- Terminate a statement sequence in a switch statement
- Exit a loop
Example :
class BreakExample{
public static void main(String args[]){
for(int count=1;count<=100;count++;{
if(count==10){
break;
}
System.out.println(“The value of num is : “ +count);
}
System.out.println(“Outside loop“);
}
}
Continue Statement:

Sometimes the programmer might want to continue a loop, but stop processing the
remainder of the code in its body for a particular iteration. The continue statement can be
used for such a scenario. In while and do-while loops, a continue statement can be used,
as shown in below example.
Example :
class ContinueDemo{
public static void main(String args[]){
for(int count = 1; count <= 10; count++){
System.out.println(“Value of count before : “+count);
if(count%2==0){
continue;
}
System.out.println(“Value of count after : “+count);
}
}
}

33. Define Return Statement with example


The return statement is used to immediately quit the current method and return to the
calling method. It is mandatory to use a return statement for non-void methods to return a
value.

public class ReturnDemo


{

MC5304-programming with java 5119/PEC/MCA


12

public static void main( String[] args )


{
ReturnDemo returnDemo = new ReturnDemo();
System.out.println( "No : " + returnDemo.returnCall() );
}
int returnCall()
{
return 5;
}
}

34. List the fundamental concepts of OOPS

 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
 Message Parsing

35. Differentiate Object and Classes

 Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors – wagging the tail, barking, eating. An object is an
instance of a class.
 Class - A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.A class is a group of objects which have
common properties. It is a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.

36. List the Rules for Java Class:


 A class can have only public or default(no modifier) access specifier.
 It can be either abstract, final or concrete (normal class).
 It must have the class keyword, and class must be followed by a legal identifier.
 It may optionally extend one parent class. By default, it will extend
java.lang.Object.
 It may optionally implement any number of comma-separated interfaces.
 The class's variables and methods are declared within a set of curly braces {}.
 Each .java source file may contain only one public class. A source file may
contain any number of default visible classes.

37. List the variables that a class can contain

 Local variables: Variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.

MC5304-programming with java 5119/PEC/MCA


13

 Instance variables: Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.

 Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.

38. Define constructor with example


When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the
Java compiler builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule
of constructors is that they should have the same name as the class. A class can have
more than one constructor.

Following is an example of a
constructor:

public class Puppy{


public Puppy(){
}
Public Puppy(String name){
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one instance
of a class.

39. How will you create an object?


There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' keyword is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Puppy myPuppy = new Puppy( "tommy" );

40. How will you Access Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path:

/* First create an object */ ObjectReference


= new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

MC5304-programming with java 5119/PEC/MCA


14

41. Define inheritance


Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).
42. State the need of extends Keyword
extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.
Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

43. What is IS-A Relationship?


IS-A is a way of saying: This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.
public class Animal {
}
public class Mammal extends Animal {
}
public class Reptile extends Animal {
}
public class Dog extends Mammal {
}
Now, based on the above example, in Object-Oriented terms, the following are true −

 Animal is the superclass of Mammal class.


 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say −
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence: Dog IS-A Animal as well
With the use of the extends keyword, the subclasses will be able to inherit all the
properties of the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.

MC5304-programming with java 5119/PEC/MCA


15

44. What is HAS-A relationship?


These relationships are mainly based on the usage. This determines whether a certain
class HAS-A certain thing. This relationship helps to reduce duplication of code as well
as bugs.
Lets look into an example −
Example

public class Vehicle{}


public class Speed{}

public class Van extends Vehicle {


private Speed sp;
}
45. List the Types of Inheritance
There are various types of inheritance as demonstrated below.

46. Define Package

A Package can be defined as a grouping of related types (classes, interfaces,


enumerations and annotations ) providing access protection and namespace management.

MC5304-programming with java 5119/PEC/MCA


16

Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes


 java.io − classes for input , output functions are bundled in this package

47. Give short note on Access Protection:

48. Define interface

An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default methods and
static methods.

49. Differentiate interface and class


However, an interface is different from a class in several ways, including −

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

50. How will you Declare Interfaces?


The interface keyword is used to declare an interface. Here is a simple example to declare an
interface −
Following is an example of an interface −
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations\
}

MC5304-programming with java 5119/PEC/MCA


17

51. List out the properties of Interfaces

 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.

52. How will you Implement Interfaces

When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

When implementation interfaces, there are several rules −

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another
class.
53. How will you Extend Interfaces?
An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

MC5304-programming with java 5119/PEC/MCA


18

54. Differentiate Autoboxing and Unboxing

Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to
an Integer, a double to a Double, and so on. If the conversion goes the other way, this is
called unboxing. Here is the simplest example of autoboxing:

55. Define variable length arguments


. A method that takes a variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded
method(one for each) and another put the arguments into an array, and then pass this array to
the method. Both of them are potentially error-prone and require more code. The varargs
feature offers a simpler, better option.
Syntax of varargs :
A variable-length argument is specified by three periods(…). For Example,
public static void fun(int ... a)
{
// method body
}

56. What is Exception Handling?


An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. When an error occurs within a method, the method creates
an object and hands it off to the runtime system. The object, called an exception object,
contains information about the error, including its type and the state of the program when
the error occurred.

Creating an exception object and handing it to the runtime system is called throwing an
exception.
The set of possible "somethings" to handle the exception is the ordered list of methods
that had been called to get to the method where the error occurred. The list of methods is
known as the call stack
The runtime system searches the call stack for a method that contains a block of code that
can handle the exception. This block of code is called an exception handler

57.List out the Types of Exception:

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception: A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored at
the time of compilation, the programmer should take care of (handle) these exceptions.

MC5304-programming with java 5119/PEC/MCA


19

2) Unchecked Exception: An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError


etc.

UNIT II
COLLECTIONS AND ADVANCE FEATURES

Utility Packages- Introduction to collection –Hierarchy of Collection framework – Generics,


Array list, LL, HashSet, Treeset, HashMap – Comparators – Java annotations – Premain
method.

1. List out the Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

2. What is utility packages?

The package java.util contains a number of useful classes and interfaces. Although the name
of the package might imply that these are utility classes, they are really more important than
that. In fact, Java depends directly on several of the classes in this package, and many
programs will find these classes indispensable. The classes and interfaces in java.util include:

 The Hashtable class for implementing hashtables, or associative arrays.


 The Vector class, which supports variable-length arrays.
 The Enumeration interface for iterating through a collection of elements.
 The StringTokenizer class for parsing strings into distinct tokens separated by delimiter
characters.
 The EventObject class and the EventListener interface, which form the basis of the new
AWT event model in Java 1.1.
 The Locale class in Java 1.1, which represents a particular locale for internationalization
purposes.
 The Calendar and TimeZone classes in Java. These classes interpret the value of
a Date object in the context of a particular calendar system.
 The ResourceBundle class and its
subclasses, ListResourceBundle and PropertyResourceBundle, which represent sets of localized
data in Java 1.1.

3. Define Collection framework


A collections framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object
oriented languages, interfaces generally form a hierarchy.

MC5304-programming with java 5119/PEC/MCA


20

Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.

Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface.

4. Define The Collection Interfaces:


The collections framework defines several interfaces. This section provides an overview of
each
interface:

The Collection Interface : This enables you to work with groups of objects; it is at the top of
the collections hierarchy.

The List Interface: This extends Collection and an instance of List stores an ordered
collection of elements.

The Set: This extends Collection to handle sets, which must contain unique elements

The SortedSet : This extends Set to handle sorted sets

The Map: This maps unique keys to values.


The Map.Entry: This describes an element akey / valuepair in a map. This is an inner class of
Map.

The SortedMap: This extends Map so that the keys are maintained in ascending order.

The Enumeration: This is legacy interface and defines the methods by which you can
enumerate
obtainoneatatime the elements in a collection of objects. This legacy interface has been
superceded by Iterator.

5. Define The Collection Classes:


Java provides a set of standard collection classes that implement Collection interfaces. Some
of the classes provide full implementations that can be used as-is and others are abstract
class, providing skeletal implementations that are used as starting points for creating concrete
collections.
The standard collection classes are summarized in the following table:

1 AbstractCollection: Implements most of the Collection interface.


2 AbstractList:Extends AbstractCollection and implements most of the List interface.
3 AbstractSequentialList: Extends AbstractList for use by a collection that uses sequential
rather than random access of its elements.
4 LinkedList: Implements a linked list by extending AbstractSequentialList.
5 ArrayList: Implements a dynamic array by extending AbstractList.
6 AbstractSet: Extends AbstractCollection and implements most of the Set interface.
7 HashSet: Extends AbstractSet for use with a hash table.
8 LinkedHashSet:Extends HashSet to allow insertion-order iterations.

MC5304-programming with java 5119/PEC/MCA


21

9 TreeSet : Implements a set stored in a tree. Extends AbstractSet.


10 AbstractMap : Implements most of the Map interface.
11 HashMap : Extends AbstractMap to use a hash table.
12 TreeMap : Extends AbstractMap to use a tree.
13 WeakHashMap: Extends AbstractMap to use a hash table with weak keys.
14 LinkedHashMap : Extends HashMap to allow insertion-order iterations.
15 IdentityHashMap : Extends AbstractMap and uses reference equality when comparing
documents.

6. Define The Collection Algorithms:


The collections framework defines several algorithms that can be applied to collections and
maps. These algorithms are defined as static methods within the Collections class.
Several of the methods can throw a ClassCastException, which occurs when an attempt is
made
to compare incompatible types, or an UnsupportedOperationException, which occurs
when an
attempt is made to modify an unmodifiable collection.
Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP.
All are immutable.

7. How to use an Iterator ?


Often, you will want to cycle through the elements in a collection. For example, you might
want to display each element.
The easiest way to do this is to employ an iterator, which is an object that implements either
the
Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements.
ListIterator
extends Iterator to allow bidirectional traversal of a list and the modification of elements.

8. How to use a Comparator ?


Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that
defines precisely what sorted order means.
This interface lets us sort a given collection any number of different ways. Also this interface
can be used to sort any instances of any class evenclasseswecannotmodify.

9. Define Java collections: List


A List is an ordered Collection of elements which may contain duplicates. It is an interface
that extents the Collection interface. Lists are further classified into the following:

1. ArrayList
2. LinkedList
3. Vectors

MC5304-programming with java 5119/PEC/MCA


22

10. .Construct the Java Collection Framework Hierarchy


As we have learned Java collection framework includes interfaces and classes. Now, let us see
the Java collections framework hierarchy.

11. Define Array list:


ArrayList is the implementation of List Interface where the elements can be dynamically
added or removed from the list. Also, the size of the list is increased dynamically if the
elements are added more than the initial size.
Syntax:
ArrayList object = new ArrayList ();

12. List Some of the methods in array list


Method Description
boolean add(Collection c) Appends the specified element to the end of a list.

void add(int index, Object


Inserts the specified element at the specified position.
element)
void clear() Removes all the elements from this list.
Return the index in this list of the last occurrence of the specified
int lastIndexOf(Object o)
element, or -1 if the list does not contain this element.
Object clone() Return a shallow copy of an ArrayList.

Object[] toArray() Returns an array containing all the elements in the list.
Trims the capacity of this ArrayList instance to be the list’s current
void trimToSize()
size.

12. Define Linked List:


Linked List is a sequence of links which contains items. Each link contains a connection
to another link.

MC5304-programming with java 5119/PEC/MCA


23

Syntax: Linkedlist object = new Linkedlist();


Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List & Doubly Linked List

13. Define Singly Linked List:


In a singly Linked list each node in this list stores the data of the node and a pointer or
reference to the next node in the list. Refer to the below image to get a better
understanding of single Linked list.

14. Define Doubly Linked List:


In a doubly Linked list, it has two references, one to the next node and another to
previous node. You can refer to the below image to get a better understanding of doubly
linked list.

15. List Some of the methods in the linked list:


Method Description
It is used to append the specified element to the end of
boolean add( Object o)
the vector.
boolean contains(Object o) Returns true if this list contains the specified element.

void add (int index, Object element) Inserts the element at the specified element in the vector.

void addFirst(Object o) It is used to insert the given element at the beginning.

void addLast(Object o) It is used to append the given element to the end.

int size() It is used to return the number of elements in a list


Removes the first occurrence of the specified element
boolean remove(Object o)
from this list.
Returns the index of the first occurrence of the specified
int indexOf(Object element)
element in this list, or -1.
Returns the index of the last occurrence of the specified
int lastIndexOf(Object element)
element in this list, or -1.

MC5304-programming with java 5119/PEC/MCA


24

15. List some of the methods of the Vector class:


Method Description
boolean add(Object o) Appends the specified element to the end of the list.
void clear() Removes all of the elements from this list.
void add(int index, Object
Inserts the specified element at the specified position.
element)
Removes the first occurrence of the specified element from
boolean remove(Object o)
this list.
boolean contains(Object element) Returns true if this list contains the specified element.
int Returns the index of the first occurrence of the specified
indexOfObject (Object element) element in the list, or -1.
int size() Returns the number of elements in this list.
Return the index of the last occurrence of the specified
int lastIndexOf(Object o) element in the list, or -1 if the list does not contain any
element.

16. Define Java Collections: Sets


A Set refers to a collection that cannot contain duplicate elements. It is mainly used to
model the mathematical set abstraction. Set has its implementation in various classes such
as HashSet, TreeSetand LinkedHashSet.

17. Define HashSet:


Java HashSet class creates a collection that use a hash table for storage. Hashset only
contain unique elements and it inherits the AbstractSet class and implements Set
interface. Also, it uses a mechanism hashing to store the elements.

18. List some of the methods of Java HashSet class:


Method Description
boolean add(Object o) Adds the specified element to this set if it is not already present.
boolean contains(Object o) Returns true if the set contains the specified element.
void clear() Removes all the elements from the set.
boolean isEmpty() Returns true if the set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
Returns a shallow copy of the HashSet instance: the elements
Object clone()
themselves are not cloned.
Iterator iterator() Returns an iterator over the elements in this set.
int size() Return the number of elements in the set.

MC5304-programming with java 5119/PEC/MCA


25

19. Define Linked Hashset : Java LinkedHashSet class is a Hash table and Linked list
implementation of the set interface. It contains only unique elements like HashSet. Linked
HashSet also provides all optional set operations and maintains insertion order.
20. TreeSet : TreeSet class implements the Set interface that uses a tree for storage. The
objects of this class are stored in the ascending order. Also, it inherits AbstractSet class and
implements NavigableSet interface. It contains only unique elements like HashSet. In
TreeSet class, access and retrieval time are faster.
21. List some of the methods of Java TreeSet class:
Method Description
boolean addAll(Collection c) Add all the elements in the specified collection to this set.
boolean contains(Object o) Returns true if the set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
void add(Object o) Add the specified element to the set.
void clear() Removes all the elements from the set.
Object clone() Return a shallow copy of this TreeSet instance.
Object first() Return the first element currently in the sorted set.
Object last() Return the last element currently in the sorted set.
int size() Return the number of elements in the set.
22. Define generics

Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of related
types, respectively.

23. List of the rules to define Generic Methods −

 All generic method declarations have a type parameter section delimited by angle
brackets <and><and> that precedes the method's return type <E>in the next example<E>in the
next example .
 Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic type
name.
 The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type arguments.
 A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types like int, double and char like
int, double and char .

24. Define Java Comparator interface


Java Comparator interface is used to order the objects of user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequence i.e. you can sort the elements on the basis of any data
member, for example rollno, name, age or anything else.
compare() method
public int compare(Object obj1,Object obj2): compares the first object with second object.

MC5304-programming with java 5119/PEC/MCA


26

25. Define Collections class

Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But we cannot sort the elements of
List. Collections class provides methods for sorting the elements of List type elements also.

26. Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

27. Define Java annotations


In the Java computer programming language, an annotation is a form of syntactic metadata that
can be added to Java source code. Classes, methods, variables, parameters and packages may be
annotated. Like Javadoc tags, Java annotations can be read from source files.
Unlike Javadoc tags, Java annotations can also be embedded in and read from class
files generated by the compiler. This allows annotations to be retained by Java VM at run-
time and read via reflection. It is possible to create meta-annotations out of the existing ones in
Java

28. Define Premain method

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this
attribute is the name of the agent class. The agent class must implement a public static premain
method similar in principle to the main application entry point. After the Java Virtual Machine
(JVM) has initialized, each premain method will be called in the order the agents were specified,
then the real application main method will be called. Each premain method must return in order
for the startup sequence to proceed.

The premain method has one of two possible signatures. The JVM first attempts to invoke the
following method on the agent class:

public static void premain(String agentArgs, Instrumentation inst);

If the agent class does not implement this method then the JVM will attempt to invoke:

public static void premain(String agentArgs);

MC5304-programming with java 5119/PEC/MCA


27

NET/SET/GATE QUESTIONS

Following questions have been asked in NET/SET/GATE CS exam

1.In Java, when we implement an interface method, it must be declared as

A. Private
B. Protected
C. Public
D. Friend
Answer must be C public
because

 An interface is a reference type in Java, it is similar to class, it is a collection of abstract


methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
 Interfaces are meant to define the public API of a type - and only that, not its
implementation.
 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 So any method (or static member) you define in an interface is by definition public.

.2.It is desired to design an object-oriented employee record system for a company. Each
employee has a name, unique id and salary. Employees belong to different categories and
their salary is determined by their category. The functions to get Name, getld and compute
salary are required. Given the class hierarchy below, possible locations for these functions
are: (GATE CS 2004)
i. getld is implemented in the superclass
ii. getld is implemented in the subclass
iii. getName is an abstract function in the superclass
iv. getName is implemented in the superclass
v. getName is implemented in the subclass
vi. getSalary is an abstract function in the superclass
vii. getSalary is implemented in the superclass
viii. getSalary is implemented in the subclass

Choose the best design


(a) (i), (iv), (vi), (viii)
(b) (i), (iv), (vii)
(c) (i), (iii), (v), (vi), (viii)
(d) (ii), (v), (viii)
Answer (a)
Getid() and GetName() can be there in the base class as these functions have the same
implementation for all subclasses. As the question says that every employee must have salary
and salary is determined by their category, getSalary() must be there as an abstract function in
base class. And all subclasses should implement salary according to their category.

3.Which one of the following are essential features of an object-oriented programming


language? (GATE CS 2005)

MC5304-programming with java 5119/PEC/MCA


28

(i) Abstraction and encapsulation


(ii) Strictly-typedness
(iii) Type-safe property coupled with sub-type rule
(iv) Polymorphism in the presence of inheritance
(a) (i) and (ii) only
(b) (i) and (iv) only
(c) (i), (ii) and (iv) only
(d) (i), (iii) and (iv) only
Answer (b)
Abstraction, Encapsulation, Polymorphism and Inheritance are the essential features of a OOP
Language

4. Predict the output of following Java Program


class Test {
public static void main(String args[]) {
int x = -4;
System.out.println(x>>1);
int y = 4;
System.out.println(y>>1);
}
}

(A) Compiler Error: Operator >> cannot be applied to negative numbers


(B)
-2
2
(C)
2
2
(D)
0
2

Answer: (B)
4.
class Test {
public static void main(String args[]) {
int x = -1;
System.out.println(x>>>29);
System.out.println(x>>>30);
System.out.println(x>>>31);
}
}
(A)
7
3

MC5304-programming with java 5119/PEC/MCA


29

1
(B)
15
7
3
(C)
0
0
0
(D)
1
1
1

Answer: (A)
5.
class Test {
public static void main(String args[]) {
System.out.println(10 + 20 + "GeeksQuiz");
System.out.println("GeeksQuiz" + 10 + 20);
}
}
(A)
30GeeksQuiz
GeeksQuiz30
(B)
1020GeeksQuiz
GeeksQuiz1020
(C)
30GeeksQuiz
GeeksQuiz1020
(D)
1020GeeksQuiz
GeeksQuiz30

Answer: (C)

Explanation: In the given expressions 10 + 20 + “GeeksQuiz” and “GeeksQuiz” + 10 + 20 ,


there are two + operators, so associativity comes to the picture. The + operator is left to right. So
the first expression is evaluated as (10 + 20) + “GeeksQuiz” and second expression is evaluated
as (“GeeksQuiz” + 10) + 20 .

MC5304-programming with java 5119/PEC/MCA


30

6. Which of the following is not an operator in Java?


(A) instanceof
(B) sizeof
(C) new
(D) >>>=

Answer: (B)
Explanation: There is no sizeof operator in Java. We generally don’t need size of objects.

7.Predict the output of following Java program?


class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t;
System.out.println(t.i);
}
Run on IDE
(A) 0
(B) garbage value
(C) compiler error
(D) runtime error

Answer: (C)

Explanation: t is just a reference, the object referred by t is not allocated any memory. Unlike
C++, in Java all non-primitive objects must be explicitly allocated and these objects are allocated
on heap. The following is corrected program.
class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.i);
}

8. Predict the output of following Java program

// Note static keyword after import.


import static java.lang.System.*;
class StaticImportDemo
{
public static void main(String args[])
{

MC5304-programming with java 5119/PEC/MCA


31

out.println("GeeksforGeeks");
}
}

(A) Compiler Error


(B) Runtime Error
(C) GeeksforGeeks
(D) None of the above

Answer: (C)

9. Which of the following is/are true about packages in Java?

1) Every class is part of some package.


2) All classes in a file are part of the same package.
3) If no package is specified, the classes in the file
go into a special unnamed package
4) If no package is specified, a new package is created with
folder name of class and the class is put in this package.

(A) Only 1, 2 and 3


(B) Only 1, 2 and 4
(C) Only 4
(D) Only 1 and 3

Answer: (A)

Explanation: In Java, a package can be considered as equivalent to C++ language’s namespace.


10. Predict the output of the following program.
class Test
{ int count = 0;

void A() throws Exception


{
try
{
count++;
try
{
count++;
ty
{
count++;
throw new Exception();
}
MC5304-programming with java 5119/PEC/MCA
32

catch(Exception ex)
{
count++;
throw new Exception();
}
}
catch(Exception ex)
{
count++;
}
}

catch(Exception ex)
{
count++;
}

void display()
{
System.out.println(count);
}

public static void main(String[] args) throws Exception


{
Test obj = new Test();
obj.A();
obj.display();
}
}
Run on IDE
(A) 4
(B) 5
(C) 6
(D) Compilation error

Answer: (B)

Explanation: ‘throw’ keyword is used to explicitly throw an exception.


In third try block, exception is thrown. So, control goes in catch block.
Again, in catch block exception is thrown. So, control goes in inner catch block.

MC5304-programming with java 5119/PEC/MCA

Das könnte Ihnen auch gefallen