0% found this document useful (0 votes)
99 views

Core-Java Notes by DK

The document discusses core object-oriented programming concepts in Java like abstraction, encapsulation, inheritance, polymorphism and interfaces. It provides definitions and explanations of these concepts along with examples. Key topics covered include method overloading, overriding, the use of the 'super' keyword, preventing method overriding using 'final' and that interfaces cannot be instantiated directly.

Uploaded by

Rajesh Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Core-Java Notes by DK

The document discusses core object-oriented programming concepts in Java like abstraction, encapsulation, inheritance, polymorphism and interfaces. It provides definitions and explanations of these concepts along with examples. Key topics covered include method overloading, overriding, the use of the 'super' keyword, preventing method overriding using 'final' and that interfaces cannot be instantiated directly.

Uploaded by

Rajesh Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Core java

by
Debasis
Kamila
9432208397

1
DEBASIS KAMILA 9875470352
1. What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest.
They are:

 Abstraction
 Polymorphism
 Inheritance
 Encapsulation
(i.e. easily remembered as A-PIE).

2. What is Abstraction?

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

3. What is Encapsulation?

Encapsulation is a technique used for hiding the properties and behaviors of an object and
allowing outside access only as appropriate. It prevents other objects from directly altering or
accessing the properties or methods of the encapsulated object.

4. What is the difference between abstraction andencapsulation?

 Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation
(information hiding) prevents clients from seeing it’s inside view, where the behavior of
the abstraction isimplemented.
 Abstraction solves the problem in the design side while Encapsulation isthe
Implementation.
 Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about
grouping up your abstraction to suit the developerneeds.

5. What is Inheritance?
 Inheritance is the process by which objects of one class acquire the properties of objects
of anotherclass.
 A class that is inherited is called asuperclass.
 The class that does the inheriting is called a subclass.

2
DEBASIS KAMILA 9875470352
 Inheritance is done by using the keywordextends.
 The two most common reasons to use inheritanceare:
o To promote code reuse
o To usepolymorphism

6. What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a
characteristic of being able to assign a different meaning or usage to something in different
contexts - specifically, to allow an entity such as a variable, a function, or an object to have
more than one form.

7. How does Java implementpolymorphism?

(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).


Polymorphism manifests itself in Java in the form of multiple methods having the same name.

 In some cases, multiple methods have the same name, but different formal
argument lists (overloadedmethods).
 In other cases, multiple methods have the same name, same return type, and same formal
argument list (overriddenmethods).

8. Explain the different forms ofPolymorphism.

There are two types of polymorphism one is Compile time polymorphism and the other is run
time polymorphism. Compile time polymorphism is method overloading. Runtime time
polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct
forms in Java:

 Method overloading
 Method overriding through inheritance
 Method overriding through the Java interface

9. What is runtime polymorphism or dynamic methoddispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an


3
DEBASIS KAMILA 9875470352
overridden method is resolved at runtime rather than at compile-time. In this process, an
overridden method is called through the reference variable of a superclass. The determination of
the method to be called is based on the object being referred to by the reference variable.

10. What is DynamicBinding?


Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding (also known as late binding) means that the code associated with a given
procedure call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.

11. What is methodoverloading?

Method Overloading means to have two or more methods with same name in the same class with
different arguments. The benefit of method overloading is that it allows you to implement
methods that support the same semantic operation but differ by argument number or type.
Note:

 Overloaded methods MUST change the argument list


 Overloaded methods CAN change the returntype
 Overloaded methods CAN change the accessmodifier
 Overloaded methods CAN declare new or broader checkedexceptions
 A method can be overloaded in the same class or in asubclass

12. What is methodoverriding?

Method overriding occurs when sub class declares a method that has the same type arguments as
a method declared by one of its superclass. The key benefit of overriding is the ability to define
behavior that’s specific to a particular subclass type.
Note:

 The overriding method cannot have a more restrictive access modifier than the method
being overridden (Ex: You can’t override a method marked public and make
itprotected).
 You cannot override a method markedfinal
 You cannot override a method marked static

4
DEBASIS KAMILA 9875470352
13. What are the differences between method overloading and methodoverriding?

Overloaded Method Overridden Method


Arguments Must change Must not change
Return type Can change Can’t change except for
covariant returns
Exceptions Can change Can reduce or eliminate. Must
not throw new or broader
checked exceptions
Access Can change Must not make more restrictive
(can be less restrictive)
Invocation Reference type determines Object type determines
which overloaded version is which method is selected.
selected. Happens at runtime.
Happens at compile time.

14. Can overloaded methods be overridetoo?

Yes, derived classes still can override the overloaded methods. Polymorphism can still happen.
Compiler will not binding the method calls since it is overloaded, because it might be
overridden now or in the future.

15. Is it possible to override the main method?

NO, because main is a static method. A static method can't be overridden in Java.

16. How to invoke a superclass version of an Overridden method?

To invoke a superclass method that has been overridden in a subclass, you must either call the
method directly through a superclass instance, or use the super prefix in the subclass itself.
From the point of the view of the subclass, the super prefix provides an explicit reference to
the superclass' implementation of the method.

// From subclass
super.overriddenMethod();
5
DEBASIS KAMILA 9875470352
17. What is super?

super is a keyword which is used to access the method or member variables from the superclass.
If a method hides one of the member variables in its superclass, the method can refer to the
hidden variable through the use of the super keyword. In the same way, if a method overrides
one of the methods in its superclass, the method can invoke the overridden method through the
use of the super keyword.
Note:

 You can only go back one level.


 In the constructor, if you use super(), it must be the very first code, and you cannot
access any this.xxxvariables or methods to compute its parameters.

18. How do you prevent a method from beingoverridden?


To prevent a specific method from being overridden in a subclass, use the final modifier on the
method declaration, which means "this is the final implementation of this method", the end of its
inheritance hierarchy.

public final void exampleMethod() {


// Methodstatements
}

19. What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must


have.
Note:

 You can’t mark an interface asfinal.


 Interface variables must bestatic.
 An Interface cannot extend anything but another interfaces.

20. Can we instantiate aninterface?

You can’t instantiate an interface directly, but you can instantiate a class that implements an
6
DEBASIS KAMILA 9875470352
interface.

21. Can we create an object for aninterface?

Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot
be instantiated in their own right, so you must write a class that implements the interface and
fulfill all the methods defined in it.

22. Do interfaces have membervariables?

Interfaces may have member variables, but these are implicitly public, static, and final- in other
words, interfaces can declare only constants, not instance variables that are available to all
implementations and may be used as key references for method arguments for example.

23. What modifiers are allowed for methods in anInterface?

Only publicand abstractmodifiers are allowed for methods in interfaces.

24.What is a marker interface?

Marker interfaces are those which do not declare any required methods, but signify their
compatibility with certain operations. The java.io.Serializable interface and Cloneableare typical
marker interfaces. These do not contain any methods, but classes must implement this interface
in order to be serialized and de-serialized.

25. What is an abstractclass?

Abstract classes are classes that contain one or more abstract methods. An abstract method
is a method that is declared, but contains no implementation.
Note:

7
DEBASIS KAMILA 9875470352
 If even a single method is abstract, the whole class must be declaredabstract.
 Abstract classes may not be instantiated, and require subclasses to provide
implementations for the abstractmethods.
 You can’t mark a class as both abstract andfinal.

26. Can we instantiate an abstractclass?

An abstract class can never be instantiated. Its sole purpose is to be extended


(subclassed).

27. What are the differences between Interface and Abstractclass?

Abstract Class Interfaces

An abstract class can provide complete,


An interface cannot provide any code
default code and/or just the details that
at all,just the signature.
have to be overridden.
In case of abstract class, a class may
A Class may implement several interfaces.
extend only one abstract class.
An abstract class can have non-
All methods of an Interface are abstract.
abstract methods.
An abstract class can have
An Interface cannot have instance
instance variables.
variables.
An abstract class can have any An Interface visibility must be public
visibility: public, private, protected. (or) none.
If we add a new method to an abstract If we add a new method to an Interface
class then we have the option of then we have to track down all the
providing default implementation and implementations of the interface and
therefore all the existing code might define implementation for the new
work properly. method.
An abstract class can contain constructors An Interface cannot contain constructors .
.
Interfaces are slow as it requires extra
Abstract classes are fast. indirection to find corresponding

8
DEBASIS KAMILA 9875470352
method in the actual class.

28. When should I use abstract classes and when should I use interfaces?

Use Interfaces when“

 You see that something in your design will changefrequently.


 If various implementations only share method signatures then it is better to use
Interfaces.
 you need some classes to use some methods which you don't want to be included in the
class, then you go for the interface, which makes it easy to just implement and make use
of the methods defined in the interface.

Use Abstract Class when“

 If various implementations are of the same kind and use common behavior or status
then abstract class is better touse.
 When you want to provide a generalized form of abstraction and leave the
implementation task with the inheritingsubclass.
 Abstract classes are an excellent way to create planned inheritance hierarchies. They're
also a good choice for nonleaf classes in classhierarchies.

29. When you declare a method as abstract, can other nonabstract methods access it?

Yes, other nonabstract methods can access a method that you declare as abstract.

30. Can there be an abstract class with no abstract methods init?

Yes, there can be an abstract class without abstract methods.

31. What isConstructor?

9
DEBASIS KAMILA 9875470352
 A constructor is a special method whose task is to initialize the object of itsclass.
 It is special because its name is the same as the classname.
 They do not have return types, not even void and therefore they cannot return values.
 They cannot be inherited, though a derived class can call the base class
constructor.
 Constructor is invoked whenever an object of its associated class iscreated.

32. How does the Java default constructor beprovided?

If a class defined by the code does not have any constructor, compiler will automatically provide
one no-parameter-constructor (default-constructor) for the class in the byte code. The access
modifier (public/private/etc.) of the default constructor is the same as the class itself.

33. Can constructor beinherited?

No, constructor cannot be inherited, though a derived class can call the base class
constructor.

34. What are the differences between Contructors andMethods?

Constructors Methods
Purpose Create an instance of a class Group Java statements
Modifiers Cannot be abstract, final, Can be abstract, final, native,
native, static, or synchronized static, or synchronized
Return Type No return type, not even void void or a valid return type
Name Same name as the class (first Any name except the class.
letter is capitalized by Method names begin with a
convention) -- usually a noun lowercase letter by convention --
usually the name of an action
this Refers to another constructor in Refers to an instance of the
the same class. If used, it must owning class. Cannot be used by
be the first line of the static methods.
constructor

10
DEBASIS KAMILA 9875470352
super Calls the constructor of the Calls an overridden method in
parent class. If used, must be the parent class
the first line of the constructor
Inheritance Constructors are not inherited Methods are inherited

35. How are this() and super() used withconstructors?


 Constructors use this to refer to another constructor in the same class with a
different parameterlist.
 Constructors use super to invoke the superclass's constructor. If a constructoruses
super, it must use it in the first line; otherwise, the compiler willcomplain.

36. What are the differences between Class Methods and InstanceMethods?

Class Methods Instance Methods


Instance methods on the other hand

Class methods are methods which are require an instance of the class to exist

declared as static. The method can be before they can be called, so an instance

called without creating an instance of of a class needs to be created by using

the class the new keyword.


Instance methods operate on
specific instances of classes.
Class methods can only operate on
Instance methods of the class can also not
class members and not on instance
be called from within a class method
members as class methods are
unless they are being called on an
unaware of instance members.
instance of that class.
Class methods are methods which are
declared as static. The method can be Instance methods are not declared as
called without creating an instance of static.
the class.

37. How are this() and super() used withconstructors?

 Constructors use this to refer to another constructor in the same class with a
different parameterlist.
 Constructors use super to invoke the superclass's constructor. If a constructor uses super,
11
DEBASIS KAMILA 9875470352
it must use it in the first line; otherwise, the compiler willcomplain.

38. What are AccessSpecifiers?

One of the techniques in object-oriented programming is encapsulation. It concerns the hiding


of data in a class and making this class available only through methods. Java allows you to
control access to classes, methods, and fields via so-called access specifiers..

39. What are Access Specifiers available inJava?

Java offers four access specifiers, listed below in decreasing accessibility:

 Public- public classes, methods, and fields can be accessed fromeverywhere.


 Protected- protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes of the
samepackage.
 Default(no specifier)- If you do not set access to specific level, then such a class, method,
or field will be accessible from inside the same package to which the class, method, or
field belongs, but not from outside thispackage.
 Private- privatemethods and fields can only be accessed within the same class to which
the methods and fields belong. privatemethods and fields are not visible within subclasses
and are not inherited bysubclasses.

Situation public protected default private


Accessible to class
yes yes yes no
from same
package?
Accessible to class no, unless it is
yes no no
from a subclass
differentpackage?

40. What is finalmodifier?

The final modifier keyword makes that the programmer cannot change the value anymore. The

12
DEBASIS KAMILA 9875470352
actual meaning depends on whether it is applied to a class, a variable, or a method.

 finalClasses- A final class cannot have subclasses.


 finalVariables- A final variable cannot be changed once it isinitialized.
 finalMethods- A final method cannot be overridden bysubclasses.

41. What are the uses of finalmethod?

There are two reasons for marking a method as final:

 Disallowing subclasses to change the meaning of themethod.


 Increasing efficiency by allowing the compiler to turn calls to the method into inline
Javacode.

42. What is staticblock?

Static block which exactly executed exactly once when the class is first loaded into JVM. Before
going to the main method the static block will execute.

43. What are staticvariables?


Variables that have only one copy per class are known as static variables. They are not
attached to a particular instance of a class but rather belong to a class as a whole. They are
declared by using the static keyword as a modifier.

statictype varIdentifier;

where, the name of the variable is varIdentifier and its data type is specified by type. Note:
Static variables that are not explicitly initialized in the code are automatically initialized with
a default value. The default value depends on the data type of the variables.

44. What is the difference between static and non-staticvariables?

A static variable is associated with the class as a whole rather than with specific instances of a
class. Non-static variables take on unique values with each object instance.
13
DEBASIS KAMILA 9875470352
45. What are staticmethods?

Methods declared with the keyword static as modifier are called static methods or class methods.
They are so called because they affect a class as a whole, not a particular instance of the class.
Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:

 A static method can only call other staticmethods.


 A static method must only access staticdata.
 A static method cannot reference to the current object using keywords superor this.

46. What is an Iterator ?

 The Iterator interface is used to step through the elements of aCollection.


 Iterators let you process each element of aCollection.
 Iterators are a generic way to go through all the elements of a Collection no matter
how it isorganized.
 Iterator is an Interface implemented a different way for everyCollection.

47. How do you traverse through a collection using itsIterator?

To use an iterator to traverse through the contents of a collection, follow these steps:
 Obtain an iterator to the start of the collection by calling thecollection’s
iterator() method.
 Set up a loop that makes a call to hasNext(). Have the loop iterate as longas
hasNext() returns true.
 Within the loop, obtain each element by callingnext().

48. How do you remove elements duringIteration?

Iterator also has a method remove() when remove is called, the current element in the
iteration is deleted.
14
DEBASIS KAMILA 9875470352
49. What is the difference between Enumeration andIterator?

Enumeration Iterator
Enumeration doesn't have a Iterator has a remove() method
remove() method
Enumeration acts as Read-only Can be abstract, final, native, static, or
interface, because it has the methods synchronized
only to traverse and fetch the objects

Note: So Enumeration is used whenever we want to make Collection objects as Read- only.

50. How isListIterator?

ListIteratoris just like Iterator, except it allows us to access the collection in either the forward
or backward direction and lets us modify an element

51. What is the Listinterface?

 The List interface provides support for ordered collections ofobjects.


 Lists may contain duplicateelements.
52. What are the main implementations of the List interface ? The main

implementations of the List interface are as follows:

ArrayList: Resizable-array implementation of the List interface. The best all- around
implementation of the Listinterface.
Vector : Synchronized resizable-array implementation of the List interface with
additional "legacymethods."
LinkedList: Doubly-linked list implementation of the List interface. May provide better
performance than the ArrayList implementation if elements are frequently inserted or
deleted within the list. Useful for queues and double-ended queues(deques).

15
DEBASIS KAMILA 9875470352
53. What are the advantages of ArrayList over arrays?

Some of the advantages ArrayList has over arraysare:

It can grow dynamically


It provides more powerful insertion and search mechanisms thanarrays.

54. Difference between ArrayList and Vector?

ArrayList Vector
ArrayList is NOT synchronized by Vector List is synchronized by default.
default.
ArrayList can use only Iterator to Vector list can use Iterator and
access the elements. Enumeration Interface to access the
elements.
The ArrayList increases its array size A Vector defaults to doubling the size
by 50 percent if it runs out of room. of its array if it runs out of room
ArrayList has no default size. While vector has a default size of 10.

55. How to obtain Array from an ArrayList?

Array can be obtained from an ArrayList using toArray() method on ArrayList.

List arrayList = new ArrayList(); arrayList.add(…

Object a[] =arrayList.toArray();

16
DEBASIS KAMILA 9875470352
56. Why insertion and deletion in ArrayList is slow compared to LinkedList?
arrayListinternally uses and array to store the elements, when that array gets filled by inserting
elements a new array of roughly 1.5 times the size of the original array is created and all the data of
old array is copied to newarray.
During deletion, all elements present in the array after the deleted elements have to be moved one step
back to fill the space created by deletion. In linked list data is stored in nodes that have reference to
the previous node and the next node so adding element is simple as creating the node an updating the
next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast
because it involves only updating the next pointer in the node before the deleted node and updating
the previous pointer in the node after the deletednode.

57. Why are Iterators returned by ArrayList called Fail Fast ?


Because, if list is structurally modified at any time after the iterator is created, in any way except
through the iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails
quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined
time in the future.

58. How do you decide when to use ArrayList and When to useLinkedList?

If you need to support random access, without inserting or removing elements from any place
other than the end, then ArrayList offers the optimal collection. If, however, you need to
frequently add and remove elements from the middle of the list and only access the list
elements sequentially, then LinkedList offers the better implementation.

59. What is the Set interface ?

The Set interface provides methods for accessing the elements of a finite
mathematicalset
Sets do not allow duplicateelements
Contains no methods other than those inherited fromCollection
It adds the restriction that duplicate elements areprohibited
17
DEBASIS KAMILA 9875470352
Two Set objects are equal if they contain the same

60.What are the main Implementations of the Set interface?

The main implementations of the List interface are asfollows:

HashSet

18
DEBASIS KAMILA 9875470352
TreeSet
LinkedHashSet
EnumSet

61.What is a HashSet ?

A HashSet is an unsorted, unorderedSet.


It uses the hashcode of the object being inserted (so the more efficient your
hashcode() implementation the better access performance you’llget).
Use this class when you want a collection with no duplicates and you don’tcare about
order when you iterate throughit.

62. What is a TreeSet?

TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted
according to the natural order of elements or by the comparator provided at creation time.

63. What is an EnumSet?

An EnumSet is a specialized set for use with enum types, all of the elements in the
EnumSet type that is specified, explicitly or implicitly, when the set is created.

64. Difference between HashSet and TreeSet?

HashSet TreeSet
HashSet is under set interface i.e. it
TreeSet is under set i.e. it provides
does not guarantee for either sorted
elements in a sorted order (acceding
order or sequence order.
order).
We can add only similar
We can add any type of elements to
types of elements to tree
hash set.
set.

65. How do you decide when to use HashMap and when to use TreeMap?

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative.

19
DEBASIS KAMILA 9875470352
If, however, you need to traverse the keys in a sorted order, then TreeMap is your better
alternative. Depending upon the size of your collection, it may be faster to add elements to a
HashMap, then convert the map to a TreeMap for sorted key traversal.

66. Difference between HashMap and Hashtable?

HashMap Hashtabl
e
HashMap lets you have null values as HashTable does not allows null
well as one null key. values as key and value.
The iterator in the HashMap is fail-
The enumerator for the Hashtable is
safe (If you change the map while
not fail- safe.
iterating, you’ll know).
HashMap is unsynchronized. Hashtable is synchronized.

Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple
keys to be NULL. Nevertheless, it can have multiple NULLvalues.

67.How does a Hashtable internally maintain the key-valuepairs?

TreeMap actually implements the SortedMap interface which extends the Map interface. In a
TreeMap the data will be sorted in ascending order of keys according to the natural order for
the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-
Black tree data structure.

68. What Are the differentCollection Views That Maps Provide?

Maps Provide Three Collection Views.

Key Set - allow a map's contents to be viewed as a set ofkeys.


Values Collection - allow a map's contents to be viewed as a set ofvalues.
Entry Set - allow a map's contents to be viewed as a set of key-valuemappings.

20
DEBASIS KAMILA 9875470352
69.What are the differences between the Comparable and Comparator interfaces?

Comparable Compara
to
It uses the compareTo() method. t uses the compare() method.

intobjectOne.compareTo(objectTwo). int compare(ObjOne, ObjTwo)


It is necessary to modify the class A separate class can be created in
whose instance is going to be order to sort the instances.
sorted.
Only one sort sequence can be created. Many sort sequences can be created.
It used by third-party classes
It is frequently used by the API classes.
to sort instances.

70.What is an exception?

An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.

71.What is error?

An Error indicates that a non-recoverable condition has occurred that should not be caught.
Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError,
which would be reported by the JVM itself.

72. What are the advantages of using exception handling?


Exception handling provides the following advantages over "traditional" error
management techniques:

Separating Error Handling Code from "Regular"Code.


Propagating Errors Up the Call Stack.
Grouping Error Types and ErrorDifferentiation.

73.What are the types of Exceptions inJava

There are two types of exceptions in Java, unchecked exceptions and checked exceptions.

21
DEBASIS KAMILA 9875470352
Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding
class RuntimeException and its subclasses. Each method must either handle all checked exceptions by
supplying a catch clause or list each unhandled checked exception as a thrownexception.
Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions.
Class Error and its subclasses also areunchecked.

74. Why Errors are NotChecked?

A unchecked exception classes which are the error classes (Error and its subclasses) are
exempted from compile-time checking because they can occur at many points in the program
and recovery from them is difficult or impossible. A program declaring such exceptions would
be pointlessly.

75. Why Runtime Exceptions are NotChecked?

The runtime exception classes (RuntimeExceptionand its subclasses) are exempted from compile-
time checking because, in the judgment of the designers of the Java programming language,
having to declare such exceptions would not aid significantly in establishing the correctness of
programs. Many of the operations and constructs of the Java programming language can result in
runtime exceptions. The information available to a compiler, and the level of analysis the
compiler performs, are usually not sufficient to establish that such run-time exceptions cannot
occur, even though this may be obvious to theprogrammer.

22
DEBASIS KAMILA 9875470352
Requiring such exception classes to be declared would simply be an irritation to
programmers.

76. Explain the significance of try-catchblocks?

Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To
do this, we use the try and catch keywords. The try is used to define a block of code in which
exceptions may occur. One or more catch clauses match a specific exception to a block of code
that handles it.

77. What is the use of finallyblock?


The finally block encloses code that is always executed at some point after the try block, whether an
exception was thrown or not. This is right place to close files, release your network sockets,
connections, and perform any other cleanup your code requires.

Note: If the try block executes with no exceptions, the finally block is executed immediately after the
try block completes. It there was an exception thrown, the finally block executes immediately after the
proper catch block completes

78. What if there is a break or return statement in try block followed by finallyblock?

If there is a return statement in the try block, the finally block executes right after the
return statement encountered, and before the return executes.
23
DEBASIS KAMILA 9875470352
79. Can we have the try block without catch block?

Yes, we can have the try block without catch block, but finally block should follow the try
block.
Note:It is not valid to use a try clause without either a catch clause or a finally clause.

80. What is the difference throw andthrows?

throws:Used in a method's signature if a method is capable of causing an exception that it does


not handle, so that callers of the method can guard themselves against that exception. If a
method is declared as throwing a particular class of exceptions, then any other method that calls
it must either have a try-catch clause to handle that exception or must be declared to throw
that exception (or its superclass) itself.

A method that does not handle an exception it throws has to announce this:

public void myfunc(intarg) throws MyException {



}

throw:Used to trigger an exception. The exception will be caught by the nearest try- catch
clause that can catch that type of exception. The flow of execution stops immediately after
the throw statement; any subsequent statements are not executed.
To throw an user-defined exception within a block, we use the throw command:

thrownew MyException("I always wanted to throw an exception!");

81. How to create customexceptions?

By extending the Exception class or one of its subclasses.

Example:

classMyExceptionextends Exception { public


MyException() {

24
DEBASIS KAMILA 9875470352
super(); }
publicMyException(String
s) { super(s); }
}

25
DEBASIS KAMILA 9875470352
CORE JAVA BY D.K
82. What are the different ways to handle exceptions?

There are two ways to handle exceptions:


Wrapping the desired code in a try block followed by a catch block to catch the
exceptions.
List the desired exceptions in the throws clause of the method and let the caller of the
method handle thoseexceptions.

LONG QUESTION ANSWER

1. Explain the features of Java.

Compiled & Interpreted


A computer language is either compiled or interpreted. Java combines both
these approaches together to make java as a two stage systems.
 Simple
 Object oriented
 Platform independent & Portable
 Multithreading
 High Performance:
 Robust & Secure
 Distributed
2. Explain package in detail with example.

 Packages are containers for classes that are used to keep the class name space
separately.
 A unique name is to be used for each class to avoid name collisions.
Defining a package:
 To create a package, include a package command as the first statement in java
source file.
 The package statement defines a name space in which classes are stored.
Syntax: package Mypackage; Here Mypackage is the name of the package.
 We can have a hierarchy of packages.
Syntax:package pkg1[.pkg2][.pkg3];
Inside pack1 folder:

- 26 -
CORE JAVA BY D.K

package pack1;
public class
student
{
String name;
String
course; int
tot, avg;
public void initialise(String s1,String c)
{
name=s1;
course=c;
}
public void calc(int m1,int m2,int m3)
{
tot=m1+m2+m3;
avg=tot/3;
}
public void display()
{
System.out.println("\nStudent name : "
+name); System.out.println("\nCourse
: " +course);
System.out.println("\nTotal : " +tot);
System.out.println("\nAverage : " +avg);

}
}

MainClass(outside pack1)

import
java.io.*; import
pack1.*;
class packeg extends student

- 27 -
CORE JAVA BY D.K
{
public static void main(String args[])throws IOException
{
int i;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); String s,s1,s2;
int m1,m2,m3; int no;
System.out.println("\nEnter the number of
students :"); s=br.readLine();
no=Integer.parseInt(s);
for(i=1;i<=no;i++)
{
System.out.println("\nEnter Name:");
s1=br.readLine();
System.out.println("\nEnter Course
:"); s2=br.readLine();
packeg p=new packeg();
p.initialise(s1,s2);
System.out.println("\nEnter the marks
:"); m1=Integer.parseInt(br.readLine());
m2=Integer.parseInt(br.readLine());
m3=Integer.parseInt(br.readLine());
p.calc(m1,m2,m3);
p.display();
}
}
}

Q: Explain interface in detail with Example.


Defining Interfaces:
 It is basically a kind of class. Like classes, interfaces contain methods and variables.
 But the interface defines only abstract methods and final fields.
Syntax: interface interfacename {
variable declaration;
method declaration; }
Extending interfaces:
 Like classes, interfaces can also be extended.

- 28 -
CORE JAVA BY D.K
 The new sub interface will inherit all the members of the super interface.
 This is done by extends keyword.
Implementing interfaces:
Interfaces are used as ‚super classes‛ whose properties are inherited by
classes. class class-name implements interface-name
{ Body of class-name }
The class class-name implements the interface interface-
name. interface area //Interface defined
{
final static float pi=3.14;
float compute(float x,float
y);
}
Class rectangle implements area
{
public float compute(float x,float y)
{
return(x*y);
}
}
Class circle implements area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
class test
{
public static void main(String args[])
{
rectangle r=new
rectangle(); circle c=new
circle();
area a; //Interface
object a=r;
System.out.println(‚Area of

- 29 -
CORE JAVA BY D.K
rect:‛+a.compute(10,20)); a=c;
System.out.println(‚Area of circle:‛+a.compute(10,0));
}
}

3. Illustrate with an example how exception handling is done in Java.

i) Exception Handling
 A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code.
 When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error.
 That method may choose to handle the exception itself, or pass it on.
 Exceptions can be generated by the Java run-time system, or they can be
manually generated by your code. Manually generated exceptions are typically
used to report some error condition to the caller of a method.
Five keywords
try, catch, throw, throws and finally.

General form of an exception-handling block


Types of Exception: (i) Built – in Exception (ii) User defined
exception class Exc2 {
public static void main(String args[
]) { int d, a;
try { // monitor a block of
code. d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) {// catch divide-by-zero
error System.out.println("Division by zero.");
}
System.out.println("After catch statement.");

ii) What are the uses of keyword final in java?

 A java variable can be declared using the keyword final. Then the final variable can be
assigned only once.
- 30 -
CORE JAVA BY D.K 9875470352
 A variable that is declared as final and not initialized is called a blank final variable. A
blank final variable forces the constructors to initialise it.
 Java classes declared as final cannot be extended. Restricting inheritance!
 Methods declared as final cannot be overridden. In methods private is equal to final, but in
variables it is not.
 final parameters – values of the parameters cannot be changed after initialization. Do a
small java exercise to find out the implications of final parameters in method overriding.
class FinallyDemo {

// Through an exception out of the method.

static void procA() {


try
{
System.out.println("inside procA"); throw new
RuntimeException("demo");
}
finally
{
System.out.println("procA's finally");
}
}
// Return from within a try block. static
void procB() {
try
{
System.out.println("inside procB"); return;
}
finally
{
System.out.println("procB's finally");
}
}
// Execute a try block normally. static
void procC() {
try
{
System.out.println("inside procC");
}
CORE JAVA BY D.K 9875470352
finally
{
System.out.println("procC's finally");
public static void main(String args[]) { try
{
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}
}

4. Write a java program to perform the following:

(i) To find the transpose of a given matrix ‘A’


public class Trans {
public static void main(String args[]) {
// initialize the variable
int[][] a = { { 5, 1, 1 }, { 3, 6, 0 }, { 0, 5, 9 } };
// print the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
// operation for transpose
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
int temp = a[i][j];
a[i][j] = a[j][i];
CORE JAVA BY D.K 9875470352
a[j][i] = temp;
}
System.out.println();
}
System.out.println("Transpose matrix:");
// After Transpose the matrix print the
result
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {

System.out.print(a[i][j]);
}
System.out.println();
}

}
}
(ii) to find the sum of the diagonal elements for a given matrix ‘B’
import java.io.*; import
java.lang.*;
public class Sum_Diagonal
{
public static void main(String args[])throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of 2D array :");
int i=Integer.parseInt(br.readLine()); int
d[][]=new int;
int j,k;
int sum1=0,sum2=0;
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the values of 2D array of "+i+" * "+i+" matrix ");
for(j=0;j<i;j++) {
for(k=0;k<i;k++) { d[j][k]=Integer.parseInt(br1.readLine());
}
System.out.println(); }
for(j=0;j<i;j++) { for(k=0;k<i;k++)
System.out.print(d[j][k]+" ");
CORE JAVA BY D.K 9875470352
System.out.println() ; } for(j=0;j<i;j++)
{ sum1=sum1+d[j][j];
} k=i-1;
for(j=0;j<i;j++) { if(k>=0) {
sum2=sum2+d[j][k]; k--; } }
System.out.println("Sum of Digonal elements are :"+sum1+" "+sum2); }}

5. Write Java program to Check whether the given matrix is upper triangular or not.

import java.io.*; class


uppertri
{
void upper( )

{
int count;
int d[][] = { { 1, 2, 6 }, { 3, 8, 5 }, { 5, 6, 7 } };
int k = 0, j = 0;

int sum1 = 0, sum2 = 0;

for (j = 0; j < d.length; j++)


{
for (k = 0; k < d.length; k++)

System.out.print(d[j][k] + " ");

System.out.println();

}
for(i = 0; i <= d.length; i++)

{
for(j = 0; j <= d.length; j++)

{
if(i <= j)
CORE JAVA BY D.K 9875470352
{
if(d[i][j] == 0)

count++;
}
}
}
if(count == 3)

System.out.println("\nThe Matrix is upper triangular\n"); else


System.out.println ("\nThe Matrix is not upper triangular\n");
}
}
public static void main(String args[])
{
classtri c = new classtri( ); c.upper(
);

6. (i) Describe the different levels of access protection available in Java.

Java addresses four categories of visibility for class members:


 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses
 Anything declared public can be accessed from anywhere
 Anything declared private cannot be seen outside of its class.
 When a member does not have an explicit access specification, it is visible to subclasses as
well as to other classes in the same package. This is the default access.

(ii) Name and explain the uses of various bit–wise operators in Java.

Operator Name Example Result Description


a&b and 3&5 1 1 if both bits are 1.

a|b or 3|5 7 1 if either bit is 1.

a^b xor 3^5 6 1 if both bits are different.


CORE JAVA BY D.K 9875470352

~a not ~3 -4 Inverts the bits.


left Shifts the bits of n left p positions. Zero bits are
n << p 3 <<< 2 12
shift shifted into the low-order positions.

7. (i) Explain the operators in Java for arithmetic and logical shift operations. Show using a Java
program how multiplication by 2 can be implemented using a logical shift operation (DEC
2015)

Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.

With higher precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When operators of equal precedence
appear in the same expression, a rule must govern which is evaluated first.

Assignment operators are evaluated right to left.


Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -
expr ~ !
multiplicative */%
additive +-

Control Statements
The statements inside your source files are generally executed from top to bottom, in the order

that they appear. Control flow statements, however, break up the flow of execution by

employing decision making, looping, and branching, enabling your program to conditionally

execute particular blocks of code. This section describes the decision-making statements (if- then,

if-then-else, switch), the looping statements (for, while, do-while), and the branching statements

(break, continue, return) supported by the Java programming language.

The if-then and if-then-else Statements

The if-then Statement


CORE JAVA BY D.K 9875470352
The if-then statement is the most basic of all the control flow statements. It tells your program to
execute a certain section of code only if a particular test evaluates to true. For example, the
Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in
motion. One possible implementation of the applyBrakes method could be as follows:

void applyBrakes() {

// the "if" clause: bicycle must be moving if


(isMoving){

// the "then" clause: decrease current speed


currentSpeed--;
}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the
end of the if-then statement.

In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:

void applyBrakes() {

// same as above, but without braces if


(isMoving)
currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code
more brittle. If a second statement is later added to the "then" clause, a common mistake would
be forgetting to add the newly required braces. The compiler cannot catch this sort of error;
you'll just get the wrong results.
The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to

false. You could use an if-then-else statement in the applyBrakes method to take some action if
CORE JAVA BY D.K 9875470352
the brakes are applied when the bicycle is not in motion. In this case, the action is to simply
print an error message stating that the bicycle has already stopped.

void applyBrakes() { if
(isMoving) {

currentSpeed--; } else {
System.err.println("The bicycle has already stopped!");
}
}

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a
score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
public static void main(String[] args) {

int testscore = 76; char grade;

if (testscore >= 90) { grade


= 'A';
} else if (testscore >= 80) { grade = 'B';

} else if (testscore >= 70) { grade = 'C';

} else if (testscore >= 60) { grade = 'D';


} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is: Grade

=C
CORE JAVA BY D.K 9875470352
You may have noticed that the value of testscore can satisfy more than one expression in the
compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.

The switch Statement

Unlike if-then and if-then-else statements, the switch statement can have a number of possible
execution paths. A switch works with the byte, short, char, and int primitive data types. It also
works with enumerated types (discussed in Enum Types), the String class, and a few special
classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in
Numbers and Strings).

The following code example, SwitchDemo, declares an int named month whose value represents a
month. The code displays the name of the month, based on the value of month, using the switch
statement.

public class SwitchDemo {


public static void main(String[] args) {

int month = 8; String


monthString; switch (month)
{
case 1: monthString = "January"; break; case 2:
monthString = "February"; break; case 3:
monthString = "March";
break;
case 4: monthString = "April"; break; case 5:
monthString = "May";
break;
case 6: monthString = "June"; break; case 7:
monthString = "July"; break; case 8:
monthString = "August"; break;
case 9: monthString = "September"; break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
CORE JAVA BY D.K 9875470352
default: monthString = "Invalid month"; break;
}
System.out.println(monthString);
}
}
In this case, August is printed to standard output.

The while and do-while Statements

The while statement continually executes a block of statements while a particular


condition is true. Its syntax can be expressed as:

while (expression) {
statement(s)

The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the while statement executes the statement(s) in the while block. Thewhile
statement continues testing the expression and executing its block until the expression evaluates
to false. Using the while statement to print the values from 1 through 10 can be accomplished as
in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){ int count
= 1;
while (count < 11) { System.out.println("Count is: " + count);
count++;
}
}
}

You can implement an infinite loop using the while statement as follows:

while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as
follows:
CORE JAVA BY D.K 9875470352

do {
statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once, as shown in the following DoWhileDemo program:

class DoWhileDemo {
public stati void main(String[] args){
c
int = 1;
count
do {

System.out.println("Count is: " + count); count++;


} while (count < 11);
}
The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers often
refer to it as the "for loop" because of the way in which it repeatedly loops until a particular
condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination;


increment) {
statement(s)
}

When using this version of the for statement, keep in mind that:

The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.

The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
CORE JAVA BY D.K 9875470352
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:

class ForDemo {
public static void main(String[] args){ for(int i=1;
i<11; i++){
System.out.println("Count is: " + i);
}
}
}

The output of this program is:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

(ii) Demonstrate the if-else ladder using a sample Java code (DEC 2015)

Syntax : if-else-if Ladder


The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false. You could use an if-then-else statement in the applyBrakes method to take
some action if the brakes are applied when the bicycle is not in motion. In this case,
the action is to simply print an error message stating that the bicycle has already stopped.

void
applyBrak
es() { if
(isMoving
CORE JAVA BY D.K 9875470352
){
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A
for a score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
public static void main(String[] args) {

int
testscore =
76; char
grade;

if (testscore >=
90) {
grade =
'A';
} else if (testscore >= 80) { grade
= 'B';
} else if (testscore >= 70) { grade
= 'C';
} else if (testscore >= 60) { grade
= 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
CORE JAVA BY D.K 9875470352
The output from the

program is: Grade =

You may have noticed that the value of testscore can satisfy more than one expression in
the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.

8. (i) Explain how Java differs from C and C++.

How Java Differs from C


 Major Difference – Java is a Object_oriented language.
 Java doesnot include C unique stmts, keywords sizeof, typeof
 Java doesnot contain datatypes struct & union
 Java doesnot define the type modifier keywords auto, extern, register,
signed and unsigned.
How Java differs from C++
 Java is a true Object – Oriented Language while c++ is c with object-
oriented extension.
 Java does not support Operator overloading, template classes
 Java does not support multiple inheritance. This is implemented in
java called as ‚Interface‛
 Java does not use pointers , global variables.
 Java has replaced the destructor function with a finalize() function
 No header files in java

(ii) Explain the various Data types of Java.

Java defines eight simple (or elemental) types of data: byte, short, int, long,
char, float, double, and boolean. These can be put in four groups:

 Integers
 Floating-point numbers
 Characters
9. Write a Java program for constructor overloading.
CORE JAVA BY D.K 9875470352
class OverloadDemo { void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter. void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters. void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter double test(double a) { System.out.println("double a:
" + a); return a*a;
}
}
class Overload {
public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double
result;
// call all versions of test() ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
CORE JAVA BY D.K 9875470352

public class Book


{
private String isbn;
private String title;
private String author;

public Book(String isbnIn, String titleIn, String authorIn)


{
isbn = isbnIn;
title = titleIn;
author = authorIn;
}
10. Create a package called "LIBRARY", which contains one class "BOOK" to
maintain all the book information. In another program, import the package and
create two classes "STAFF" and "STUDENT" from the super class "BOOK". In the
main( ) method, create array of objects for the classes book and call the method
in book class to read the details of the available books and display the menu as 1.
staff 2. student. If the selected choice is 1, call the read method in staff class to
read the details of the staff and the books they want to take (Check whether the
given book ids are available in the book list). If the selected choice is 2, call the
read method in student dais to read details of the student and the books they
want to take (Check whether the given book ids are available in the book list).
Before issuing each book, check that the book is available is in. the library or
not. After reading the values, use the corresponding display methods to display
the details of the staff or student with the books they have taken .

public String getISBN()


{
return isbn;
}

public String getTitle()


{
return title;
}

public String getAuthor()


{
CORE JAVA BY D.K 9875470352
return author;
}
public String toString()
{
return "(" + isbn + " , " + author + ", " + title + ")\n";
}
public boolean equals (Object objIn)
{
Book bookIn = (Book) objIn; return isbn.equals(bookIn.isbn);
}
public int hashCode()
{
return isbn.hashCode();
}

}
import java.util.*;

public class Library


{
Map <String, Book> books; // declare map collection

// create empty map public Library()


{
books = new HashMap<String, Book>();
}
// add the given book into the collection public boolean addBook(Book bookIn)
{
String keyIn = bookIn.getISBN(); // isbn will be key of map if (books.containsKey(keyIn)) //
check if isbn already in use
{
return false; // indicate error
}
else // ok to add this book
{
books.put(keyIn, bookIn); // add key and book pair
into map return true;
CORE JAVA BY D.K 9875470352
}
}

// remove the book with the given


isbn public boolean
removeBook(String isbnIn)
{
if (books.remove(isbnIn)!= null) // check if item was removed
{
return true;
}
else // when item is not removed
{
return false;
}
}

// return the number of books in the


collection public int
getTotalNumberOfBooks()
{
return books.size();
}

// return the book with the given isbn or null if


no such book public Book getBook (String isbnIn)
{
return books.get(isbnIn);
}

// return the set of books in the


collection public Set<Book>
getAllBooks ()
{
Set<Book> bookSet = new HashSet<Book>(); // to store the set
of books Set<String> theKeys = books.keySet(); // get the set of
keys
CORE JAVA BY D.K 9875470352
// iterate through the keys and put each value in
the bookSet for (String isbn : theKeys)
{
Book theBook =
books.get(isbn);
bookSet.add(theBook);
}
return bookSet; // return the set of books
}
}
11. Explain in detail about Java classes and Java packages.

Class Definitions: A java program may contain multiple class definitions. classes
are the primary and essential elements of a java program
Main Method Class:- Since every java standalone program requires a main method as
its starting point, this class is the essential part of a java program.

/*
* First Java program, which says "Hello, world!"
*/
public class Hello { // Save as "Hello.java" public static void main(String[] args) {
System.out.println("Hello, world!"); // print message
}
}
 Packages are containers for classes that are used to keep the class name space separately.
 A unique name is to be used for each class to avoid name collisions.
Defining a package:
 To create a package, include a package command as the first statement in java source file.
 The package statement defines a name space in which classes are stored.
Syntax: package Mypackage; Here Mypackage is the name of the package.
 We can have a hierarchy of packages.
Syntax:package pkg1[.pkg2][.pkg3];
Inside pack1 folder:

package pack1; public class student


{
String name; String course; int tot, avg;
public void initialise(String s1,String c)
{
CORE JAVA BY D.K 9875470352
name=s1; course=c;
}
public void calc(int m1,int m2,int m3)
{
tot=m1+m2+m3; avg=tot/3;
}
public void display()
{
System.out.println("\nStudent name : " +name); System.out.println("\nCourse :"
+course); System.out.println("\nTotal : " +tot); System.out.println("\nAverage
: " +avg);
}
}

MainClass(outside pack1)

import java.io.*; import pack1.*;


class packeg extends student
{
public static void main(String args[])throws IOException
{
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s,s1,s2;
int m1,m2,m3; int no;
System.out.println("\nEnter the number of students :"); s=br.readLine();
no=Integer.parseInt(s); for(i=1;i<=no;i++)
{
System.out.println("\nEnter Name:"); s1=br.readLine(); System.out.println("\nEnter Course
:"); s2=br.readLine();
packeg p=new packeg(); p.initialise(s1,s2); System.out.println("\nEnter the marks :");
m1=Integer.parseInt(br.readLine()); m2=Integer.parseInt(br.readLine());
m3=Integer.parseInt(br.readLine()); p.calc(m1,m2,m3);
p.display();
}
}

13. Discuss about the expressions, operators and various control structures in Java.
CORE JAVA BY D.K 9875470352
Operators

Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.

with higher precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When operators of equal precedence
appear in the same expression, a rule must govern which is evaluated first.

assignment operators are evaluated right to left.


Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -
expr ~ !
multiplicative */%
additive +-

shift << >> >>>


relational < > <= >=
instanceof
equality == !=
bitwise &
AND
bitwise ^
exclusive
OR
bitwise |
inclusive
OR
logical &&
AND
logical OR ||
ternary ?:

Control Statements
The statements inside your source files are generally executed from top to bottom, in the

order that they appear. Control flow statements, however, break up the flow of execution
CORE JAVA BY D.K 9875470352
by employing decision making, looping, and branching, enabling your program to

conditionally execute particular blocks of code. This section describes the decision-making

statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and

the branching statements (break, continue, return) supported by the Java programming

language.

The if-then and if-then-else Statements The if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true. For
example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if
the bicycle is already in motion. One possible implementation of the applyBrakes method
could be as follows:

void applyBrakes() {

// the "if" clause: bicycle must be moving if (isMoving){

// the "then" clause: decrease current speed currentSpeed--;


}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to
the end of the if-then statement.

In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:

void applyBrakes() {

// same as above, but without braces if (isMoving)


currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make
CORE JAVA BY D.K 9875470352
the code more brittle. If a second statement is later added to the "then" clause, a common
mistake would be forgetting to add the newly required braces. The compiler cannot catch
this sort of error; you'll just get the wrong results.

The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates

to false. You could use an if-then-else statement in the applyBrakes method to take some
action if the brakes are applied when the bicycle is not in motion. In this case, the action
is to simply print an error message stating that the bicycle has already stopped.

void applyBrakes() { if (isMoving) {


currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}

The following program, IfElseDemo, assigns a grade based on the value of a test score: an
A for a score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
public static void main(String[] args) {
int testscore = 76; char grade;

if (testscore >= 90) { grade = 'A';


} else if (testscore >= 80) { grade
= 'B';
} else if (testscore >= 70) { grade
= 'C';
} else if (testscore >= 60) { grade
= 'D';
} else {
CORE JAVA BY D.K 9875470352
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is: Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in
the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated.

The switch Statement

Unlike if-then and if-then-else statements, the switch statement can have a number of
possible execution paths. A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types (discussed in Enum Types), the String class,
and a few special classes that wrap certain primitive types: Character, Byte, Short, and
Integer (discussed in Numbers and Strings).

The following code example, SwitchDemo, declares an int named month whose value
represents a month. The code displays the name of the month, based on the value of
month, using the switch statement.

public class SwitchDemo {


public static void main(String[] args) {
int month = 8; String monthString; switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April"; break;
case 5: monthString = "May"; break;
CORE JAVA BY D.K 9875470352
case 6: monthString = "June"; break;
case 7: monthString = "July"; break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default:monthString = "Invalid month"; break;
}
System.out.println(monthString);
}
}
In this case, August is printed to standard output.

The while and do-while Statements

The while statement continually executes a block of statements while a particular ondition
is true. Its syntax can be expressed as:

while (expression) {
statement(s)
}

The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. Thewhile statement continues testing the expression and executing its block until
the expression evaluates to false. Using the while statement to print the values from 1
through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {

public static void main(String[] args){ int count = 1;

while (count < 11) { System.out.println("Count is: "


+ count); count++;
}
}
CORE JAVA BY D.K 9875470352
}
You can implement an infinite loop using the while statement as follows:

while (true){
// your code goes here
}

The Java programming language also provides a do-while statement, which can be
expressed as follows:

do {
statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once.
The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed as
follows:

for (initialization; termination; increment) {


statement(s)
}

When using this version of the for statement, keep in mind that:

The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.

The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
CORE JAVA BY D.K 9875470352
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:

class ForDemo {
public static void main(String[] args){ for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}

The output of this program is:


Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
14. i) Explain Any Two Control Structure Supported By Java with Suitable Example (DEC 2016)
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. Java’s program control
statements can be put into the following categories:
Selection iteration jump
Selection statements
Selection statements allows program to choose different paths of execution based upon
the outcome of an expression or the state of a variable.
Iteration statements
Iteration statements enable program execution to repeat one or more statements
(that is, iteration statements form loops).
Jump statements
Jump statements allows program to execute in a nonlinear fashion. All of Java’s
control statements are examined here.
Selection Statements
1. if Statement
The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if
statement: if (condition)
CORE JAVA BY D.K 9875470352
{ statement1; }
else { statement2; }
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block). The condition is any expression that returns a boolean value.
The else clause is optional. The if statement works like this:
If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is
executed.
Solution:
Example
class Man { public static void main(String args[]){ int age= 49;
if(age>=35) System.out.println("Old"); else System.out.println("Young");
}}
Output: Old
2. Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are
very common in programming. When you nest ifs, the main thing to remember is that an
else statement always refers to the nearest if statement that is within the same block as
the else and that is not already associated with an else.
3. The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is
the if-else-if ladder. It looks like this:
if (condition1) statement1;
else if (condition2)
statement2; “““““““““.. “““““““““..
else statement3;
The if statements are executed from the top to down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Example
class Result { public static void main(String args[])
{
int mark= 76;
if(mark>=60) System.out.println("1st Division");
else if(mark>=50 && mark<60) System.out.println("2nd Division"); else
System.out.println("3rd Division"); } }
Output: 1st Division
Switch Statements
CORE JAVA BY D.K 9875470352
The switch statement is Java’s multi way branch statement. It provides an easy way
to dispatch execution to different parts of your code based on the value of an expression.
As such, it often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression)
{
case value1: // statement sequence break
; case value2: // statement sequence break;
... case valueN:
// statement sequence break; default: // default statement sequence
}
Solution:
class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++) switch(i)
{
case 0: System.out.println("i is zero."); break;
case 1: System.out.println("i is one."); break;
case 2: System.out.println("i is two."); break;
case 3: System.out.println("i is three."); break;
default: System.out.println("i is greater than 3."); } } } Output:
i is zero. i is one. i is two. i is three. i is greater than 3. i is greater than 3.

14. ii) Declare An Interface Called Sports With Appropritate Methods. Design And
Implements Football And Volleyball Interface Which Extends Sports Interface. Write Java
Classes Which Implements Football And Volleyball Interface.
Interface sports{
Float Sport_wt=10.0f;
}
Interface football
{
Void putplayer();} Interface volleyball(){ Void putplayer1();
}
Class main1{
Int f_player,v_player; Void getplayer( int p1){ F_player=p1;
CORE JAVA BY D.K 9875470352
}
Void getplayer2(int p2){ V_player=p2
}}
Class main2 extends main1 im plements sports,football,volletball{ Public void putplayer(){
Getplayer();
System.out.println(‚team football player is:‛+f_player);
}
Public void putplayer(){ Getplayer2();
System.out.println(‚team football player is:‛+v_player);
}}
Class main3{
Public static void main(String args[]){ Main2 a=new main2(); a.geplayer1(4);
a.getplayer2(10); a.putplayer1(); a.putplayer();}}

15. Explain Exception Handling in Java with appropite Examples.

Error occurred in a program can be of two types: syntax error or logical error. An
exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a run-time error.
A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code. Exception Handling is a mechanism by which exception
occurred in a program is handled.
Java exception handling is managed via five keywords:
Try Catch Thro throws finally.
Keyword and their meaning
catch block If an exception occurs within the try block, it is throws an exception to
the catch block which handle it in some rational manner.
throw To manually throw an exception, use the keyword throw.
throwsA throws clause lists the types of exceptions that a method might throw
finallyAny code that absolutely must be executed before a method returns is put in
a finally block.
Execution Flow of the try, catch and finally block
The general form of an exception-handling block is: try { // block of code to
monitor for errors }
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1 } catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2 } “““.. “““..
finally
CORE JAVA BY D.K 9875470352
{ // block of code to be executed before try block ends }
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable
is at the top of the exception class hierarchy.
The Throwable class has two subclasses Error and Exception. Error and Exception classes
are used for handling errors in java.
Object Throwable Exception AWT Error Error
SQL Exceptionn Thread
Class not Found Runtime Exception Number Format Using try and catch
The following program includes a try block and a catch clause which processes the
ArithmeticException generated by the division-by-zero error.
Example:
class Ex {
public static void main(String args[])
{
int x, y; try { x = 0; y= 1/ x; System.out.println("This will not be printed."); }} catch
(ArithmeticException e)
{
System.out.println("Division by zero."); }
System.out.println("After catch statement."); }

You might also like