Core-Java Notes by DK
Core-Java Notes by DK
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.
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.
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).
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
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:
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?
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.
NO, because main is a static method. A static method can't be overridden in Java.
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’t instantiate an interface directly, but you can instantiate a class that implements an
6
DEBASIS KAMILA 9875470352
interface.
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.
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.
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.
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.
8
DEBASIS KAMILA 9875470352
method in the actual class.
28. When should I use abstract classes and when should I use interfaces?
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.
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.
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.
No, constructor cannot be inherited, though a derived class can call the base class
constructor.
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
36. What are the differences between Class Methods and InstanceMethods?
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
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.
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.
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.
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.
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:
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().
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.
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
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?
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.
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.
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.
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
HashSet
18
DEBASIS KAMILA 9875470352
TreeSet
LinkedHashSet
EnumSet
61.What is a HashSet ?
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
A method that does not handle an exception it throws has to announce this:
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:
Example:
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?
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();
}
}
}
- 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));
}
}
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.
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 {
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.
{
int count;
int d[][] = { { 1, 2, 6 }, { 3, 8, 5 }, { 5, 6, 7 } };
int k = 0, j = 0;
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)
(ii) Name and explain the uses of various bit–wise operators in Java.
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.
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
void applyBrakes() {
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() {
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) {
=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.
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.
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 {
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:
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);
}
}
}
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)
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
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.
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
}
import java.util.*;
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:
MainClass(outside pack1)
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.
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 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() {
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() {
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 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.
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;
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.
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.
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 {
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:
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);
}
}
}
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();}}
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."); }