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

programming in java

The document provides an overview of key concepts in Java programming, including polymorphism, binding types (static and dynamic), inheritance types, and access modifiers. It explains polymorphism as the ability of a message to be displayed in multiple forms, and details static and dynamic binding with examples. Additionally, it covers inheritance mechanisms, keywords like 'this', 'super', 'final', and 'static', and includes a program to check for prime numbers.

Uploaded by

tokeye5819
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

programming in java

The document provides an overview of key concepts in Java programming, including polymorphism, binding types (static and dynamic), inheritance types, and access modifiers. It explains polymorphism as the ability of a message to be displayed in multiple forms, and details static and dynamic binding with examples. Additionally, it covers inheritance mechanisms, keywords like 'this', 'super', 'final', and 'static', and includes a program to check for prime numbers.

Uploaded by

tokeye5819
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA

ENROLLMENT NO:

Q.1: Define polymorphism with its need?

ANS:

The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one
form.
Real life example of polymorphism: A person at the same time can have
different characteristic. Like a man at the same time is a father, a husband, an
employee. So the same person possesses different behaviour in different
situations. This is called polymorphism.

Polymorphism is considered one of the important features of Object-Oriented


Programming. Polymorphism allows us to perform a single action in different
ways. In other words, polymorphism allows you to define one interface and have
multiple implementations. The word ―poly‖ means many and ―morphs‖ means
forms, So it means many forms.
Q.2: Define and explain static and dynamic binding using the program?
ANS:
Static Binding or Early Binding

The binding which can be resolved at compile time by compiler is known as


static or early binding. The binding of static, private and final methods
is compile-time. The reason is that the method cannot be overridden and the
type of the class is determined at the compile time. Let‘s see an example to
understand this:

Static binding example

Here we have two classes Human and Boy. Both the classes have same method
walk() but the method is static, which means it cannot be overridden so even
though I have used the object of Boy class while creating object ob., the parent
class method is called by it. So whenever a binding of static, private and final
methods happen, type of the class is determined by the compiler at compile time
and the binding happens then and there.

Class Human {
Public static void walk ()
{
System.out.println("Human walks");
}

CLASS: YAHOO PAGE: 1


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

}
Class Boy extends Human {
Public static void walk ()
{
System.out.println ("Boy walks");
}
Public static void main (String rags []) {
/* Reference is of Human type and object is
* Boy type
*/
Human ob. = new Boy ();
/* Reference is of Human type and object is
* Of Human type.
*/
Human obj2 = new Human ();
obj.walk ();
obj2.walk ();
}
}
Output:

Human walks
Human walks
Dynamic Binding or Late Binding

When compiler is not able to resolve the call/binding at compile time, such
binding is known as Dynamic or late binding. Method Overriding is a perfect
example of dynamic binding as in overriding both parent and child classes have
same method and in this case the type of the object determines which method
is to be executed. The type of object is determined at the run time so this is
known as dynamic binding.

Dynamic binding example

This is the same example that we have seen above. The only difference here is
that in this example, overriding is actually happening since these methods
are not static, private and final. In case of overriding the call to the overridden
method is determined at runtime by the type of object thus late binding happens.
Let‘s see an example to understand this:

Class Human {
//Overridden Method

CLASS: YAHOO PAGE: 2


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Public void walk ()


{
System.out.println ("Human walks");
}
}
Class Demo extends Human {
//Overriding Method
Public void walk (){
System.out.println ("Boy walks");
}
Public static void main (String rags []) {
/* Reference is of Human type and object is
* Boy type
*/
Human ob. = new Demo ();
/* Reference is of Human type and object is
* Of Human type.
*/
Human obj2 = new Human ();
obj.walk ();
obj2.walk ();
}
}
Output:

Boy walks
Human walks

Q.3: What is an Inheritance? Explain its types with proper diagrams and
suitable example(s)?
ANS:
Inheritance
In object-oriented programming, inheritance is the mechanism of basing
an object or class upon another object (prototype-based inheritance) or class
(class-based inheritance), retaining similar implementation. In most class-based
object-oriented languages, an object created through inheritance, a "child
object", acquires all the properties and behaviours of the "parent object" , with
the exception of: constructors, destructor, overloaded operators and friend
functions of the base class. Inheritance allows programmers to create classes
that are built upon existing classes,[1] to specify a new implementation while
maintaining the same behaviours (realizing an interface), to reuse code and to

CLASS: YAHOO PAGE: 3


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

independently extend original software via public classes and interfaces. The
relationships of objects or classes through inheritance give rise to a directed
graph.
Inheritance was invented in 1969 for simulate and is now used throughout many
object-oriented programming languages such as Java, C++ or Python.

Types
Single inheritance
Where subclasses inherit the features of one superclass. A class acquires the
properties of another class.

Multiple inheritances
Where one class can have more than one superclass and inherit features from all
parent classes.

"Multiple inheritances ... were widely supposed to be very difficult to


implement efficiently. For example, in a summary of C++ in his book
on Objective C, Brad Cox actually claimed that adding multiple inheritances to
C++ was impossible. Thus, multiple inheritances seemed more of a challenge.
Since I had considered multiple inheritances as early as 1982 and found a

CLASS: YAHOO PAGE: 4


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

simple and efficient implementation technique in 1984, I couldn't resist the


challenge. I suspect this to be the only case in which fashion affected the
sequence of events.
Multilevel inheritance
Where a subclass is inherited from another subclass. It is not uncommon that a
class is derived from another derived class as shown in the figure "Multilevel
inheritance".

The class A serves as a base class for the derived class B, which in turn serves
as a base class for the derived class C. The class B is known
as intermediate base class because it provides a link for the inheritance
between A and C. The chain ABC is known as inheritance path.

Hierarchical inheritance
This is where one class serves as a superclass (base class) for more than one sub
class. For example, a parent class, A, can have two subclasses B and C. Both B
and C's parent class is A, but B and C are two separate subclasses.
Hybrid inheritance
Hybrid inheritance is when a mix of two or more of the above types of
inheritance occurs. An example of this is when class A has a subclass B which
has two subclasses, C and D. This is a mixture of both multilevel inheritance
and hierarchal inheritance.
Q.4: Explain following keywords: this, super, final and static?
ANS:
This keyword in java

CLASS: YAHOO PAGE: 5


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this
keyword.

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer


immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. Super can be used to refer immediate parent class instance variable.
2. Super can be used to invoke immediate parent class method.
3. Super can be used to invoke immediate parent class constructor.

CLASS: YAHOO PAGE: 6


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Final Keyword In Java

1. Final variable
2. Final method
3. Final class
4. Is final method inherited
5. Blank final variable
6. Static blank final variable
7. Final parameter
8. Can you declare a final constructor

The final keyword java is used to restrict the user. The java final keyword can
be used in many contexts. Final can be:

1. variable
2. method
3. class

CLASS: YAHOO PAGE: 7


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

The final keyword can be applied with the variables, a final variable that have
no value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.

Java static keyword

1. Static variable
2. Program of the counter without static variable
3. Program of the counter with static variable
4. Static method
5. Restrictions for the static method
6. Why is the main method static?
7. Static block
8. Can we execute a program without main method?

The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

CLASS: YAHOO PAGE: 8


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

1) Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.

Q.5: Write a program which checks whether an entered number is prime


or not?

ANS:

A prime number is a positive integer that is divisible only by 1 and itself.


For example: 2, 3, 5, 7, 11, 13, and 17

CLASS: YAHOO PAGE: 9


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Program to Check Prime Number

#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

for (i = 2; i <= n / 2; ++i) {

// condition for non-prime


if (n % i == 0) {
flag = 1;
break;
}
}

if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}

return 0;
}

Output:

Enter a positive integer: 29


29 is a prime number.

CLASS: YAHOO PAGE: 10


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

In the program, a for loop is iterated from i = 2 to i < n/2.


In each iteration, whether n is perfectly divisible by i is checked using:

if (n % i == 0) {

If n is perfectly divisible by i, n is not a prime number. In this case, flag is set


to 1, and the loop is terminated using the break statement.
After the loop, if n is a prime number, flag will still being 0 However, if n is a
non-prime number, flag will be 1.

Q.6: What is an Access Specified? Explain it with a suitable example with


appropriate output in detail?

ANS:
Access modifiers (or access specifies) are keywords in object-oriented
languages that set the accessibility of classes, methods, and other members.
Access modifiers are a specific part of programming language syntax used to
facilitate the encapsulation of components.[1]
In C++, there are only three access modifiers. C# extends the number of them to
six,[2] while Java has four access modifiers,[3] but three keywords for this
purpose. In Java, having no keyword before defaults to the package-private
modifier.
When the class is declared as public, it is accessible to other classes defined in
the same package as well as those defined in other packages. This is the most
commonly used specified for classes. However, a class itself cannot be declared
as private. If no access specified is stated, the default access restrictions will be
applied. The class will be accessible to other classes in the same package but
will be inaccessible to classes outside the package. When we say that a class is
inaccessible, it simply means that we cannot create an object of that class or
declare a variable of that class type. The protected access specified too cannot
be applied to a class.

Types of Access Modifiers in Java

CLASS: YAHOO PAGE: 11


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Java provides four types of access specify that we can use with classes and other
entities.

These are:

#1) Default: Whenever a specific access level is not specified, then it is


assumed to be ‗default‘. The scope of the default level is within the package.

#2) Public: This is the most common access level and whenever the public
access specified is used with an entity, that particular entity is accessible
throughout from within or outside the class, within or outside the package, etc.

#3) Protected: The protected access level has a scope that is within the
package. A protected entity is also accessible outside the package through
inherited class or child class.

#4) Private: When an entity is private, then this entity cannot be accessed
outside the class. A private entity can only be accessible from within the class.

Default Access Specifiers

A default access modifier in Java has no specific keyword. Whenever the access
modifier is not specified, then it is assumed to be the default. The entities like
classes, methods, and variables can have a default access.

A default class is accessible inside the package but it is not accessible from
outside the package i.e. all the classes inside the package in which the default
class is defined can access this class.

The below program demonstrates the Default Access Modifier in Java.

Class Base Class

Void display () //no access modifier indicates default modifier

CLASS: YAHOO PAGE: 12


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

System.out.println ("BaseClass::Display with 'dafault' scope");

class Main

public static void main(String args[])

//access class with default scope

BaseClass obj = new BaseClass ();

obj.display (); //access class method with default scope

Output:

In the above program, we have a class and a method inside it without any access
modifier. Hence both the class and method display has default access. Then we
see that in the method, we can directly create an object of the class and call the
method.

Public Access Modifier

A class or a method or a data field specified as ‗public‘ is accessible from any


class or package in the Java program. The public entity is accessible within the

CLASS: YAHOO PAGE: 13


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

package as well as outside the package. In general, public access modifier is a


modifier that does not restrict the entity at all.

class A

Public void display ()

System.out.println ("SoftwareTestingHelp!!");

class Main

Public static void main (String args [])

A obj = new A ();

obj.display();

Output:

Protected Access Specifier

CLASS: YAHOO PAGE: 14


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

The protected access specifier allows access to entities through subclasses of the
class in which the entity is declared. It doesn‘t matter whether the class is in the
same package or different package, but as long as the class that is trying to
access a protected entity is a subclass of this class, the entity is accessible.

Note that a class and an interface cannot be protected i.e. we cannot apply
protected modifiers to classes and interfaces.
The protected access modifier is usually used in parent-child relationships.

The below program demonstrates the usage of the Protected Access


modifier in Java.
//A-&gt;B-&gt;C = class hierarchy

Class A

Protected void display ()

System.out.println ("SoftwareTestingHelp");

class B extends A {}

class C extends B {}

class Main{

public static void main(String args[])

CLASS: YAHOO PAGE: 15


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

B obj = new B (); //create object of class B

obj.display(); //access class A protected method using obj

C cObj = new C (); //create object of class C

cObj.display (); //access class A protected method using cObj

Output:

Private Access Modifier

The ‗private‘ access modifier is the one that has the lowest accessibility level.
The methods and fields that are declared as private are not accessible outside
the class. They are accessible only within the class which has these private
entities as its members.

Note that the private entities are not even visible to the subclasses of the class.
A private access modifier ensures encapsulation in Java.

Some points to be noted regarding the Private Access Modifier.

1. Private access modifier cannot be used for classes and interfaces.


2. The scope of private entities (methods and variables) is limited to the
class in which they are declared.
3. A class with a private constructor cannot create an object of the class
from any other place like the main method. (More details on private
constructors has been explained in our earlier tutorial).

The below Java program uses a Private Access Modifier.

class TestClass{

CLASS: YAHOO PAGE: 16


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

//private variable and method

private int num=100;

private void printMessage() {System.out.println("Hello java");}

public class Main {

public static void main (String args[]){

TestClass obj=new TestClass ();

System.out.println(obj.num); //try to access private data member - Compile


Time Error

obj.printMessage(); //Accessing private method - Compile Time Error

Output:

The program above gives compilation error as we are trying to access private
data members using the class object.

But there is a method to access private member variables. This method is using
getters and setters in Java. So we provide a public get method in the same class

CLASS: YAHOO PAGE: 17


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

in which private variable is declared so that getter can read the value of the
private variable.

Similarly, we provide a public setter method that allows us to set a value for the
private variable.

The following Java program demonstrates the use of getter and setter
methods for private variables in Java.

class DataClass {

private String strname;

// getter method

public String getName () {

return this.strname;

// setter method

public void setName (String name) {

this.strname= name;

public class Main {

public static void main(String[] main) {

DataClass d = new DataClass();

CLASS: YAHOO PAGE: 18


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

// access the private variable using the getter and setter

d.setName("Java Programming");

System.out.println(d.getName());

Output:

7. Differentiate Abstract class and Interface with suitable examples. What


is a collection in JAVA? Differentiate HashMap and Hashtable with
suitable examples.

ANS:

Abstract class Interface

1) Abstract class can have Interface can have only


abstract and non- abstract methods. Since Java 8, it
abstract methods. can have default and static
methods also.

2) Abstract class doesn't Interface supports multiple


support multiple inheritance. inheritance.

3) Abstract class can have Interface has only static and final
final, non-final, static and variables.
non-static variables.

4) Abstract class can provide Interface can't provide the


the implementation of implementation of abstract
interface. class.

5) The abstract keyword is The interface keyword is used to


used to declare abstract class. declare interface.

CLASS: YAHOO PAGE: 19


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

6) An abstract class can extend An interface can extend another


another Java class and Java interface only.
implement multiple Java
interfaces.

7) An abstract class can be An interface can be implemented


extended using keyword using keyword "implements".
"extends".

8) A Java abstract class can Members of a Java interface are


have class members like public by default.
private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Collections in Java

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

Hierarchy of collection framework

CLASS: YAHOO PAGE: 20


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Difference between HashMap and Hashtable

HashMap Hashtable

1) HashMap is none synchronized. It is Hashtable


not-thread safe and can't be shared between is synchronized. It is
many threads without proper thread-safe and can be
synchronization code. shared with many threads.

2) HashMap allows one null key and Hashtable doesn't allow


multiple null values. any null key or value.

3) HashMap is a new class introduced in Hashtable is a legacy class.


JDK 1.2.

CLASS: YAHOO PAGE: 21


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

4) HashMap is fast. Hashtable is slow.

5) We can make the HashMap as Hashtable is internally


synchronized by calling this code synchronized and can't be
Map m = unsynchronized.
Collections.synchronizedMap(hashMap);

6) HashMap is traversed by Iterator. Hashtable is traversed by


Enumerator and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hashtable


is not fail-fast.

8) HashMap inherits Abstract Map class. Hashtable


inherits Dictionary class.

Q.8: Differentiate String with StringBufferclass. List out the methods


available with String class and explain any five with proper JAVA code in
detail?

ANS:

Difference between String and StringBuffer

No. String StringBuffer

1) String class is immutable. StringBuffer class is


mutable.

2) String is slow and consumes StringBuffer is fast


more memory when you and consumes less
concat too many strings memory when you
because every time it cancat strings.
creates new instance.

CLASS: YAHOO PAGE: 22


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

3) String class overrides the StringBuffer class


doesn't override the
strings by equals() method.
equals () method of
Object class.

Public char charAt(int index)

This method requires an integer argument that indicates the position of the
character that the method returns.This method returns the character located at
the String's specified index. Remember, String indexes are zero-based—for
example,

String x = "airplane";
System.out.println(x.charAt(2)); // output is 'r'

Public Boolean equalsIgnoreCase(String s)

This method returns a boolean value (true or false) depending on whether the
value of the String in the argument is the same as the value of the String used to
invoke the method. This method will return true even when characters in the
String objects being compared have differing cases—for example,

String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); // is "true"
System.out.println( x.equalsIgnoreCase("tixe")); // is "false"

Public String replace (char old, char new)

This method returns a String whose value is that of the String used to invoke the
method, updated so that any occurrence of the char in the first argument is
replaced by the char in the second argument—for example,

String x = "oxoxoxox";
System.out.println( x.replace('x', 'X')); // output is ―oXoXoXoX"

Public String toLowerCase()

This method returns a String whose value is the String used to invoke the
method, but with any uppercase characters converted to lowercase—for
example,

CLASS: YAHOO PAGE: 23


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

String x = "A New Java Book";


System.out.println( x.toLowerCase() ); // output is "a new java book"

Public String toUpperCase()

This method returns a String whose value is the String used to invoke the
method, but with any lowercase characters converted touppercase—for
example,

String x = "A New Java Book";


System.out.println(x.toUpperCase()); // output is ―A NEW JAVA BOOK"

Q.9: What is an Exception? List out various built-in exceptions in JAVA


and explain any one Exception class with a suitable example?

ANS:

Exception

An Exception is an unwanted event that interrupts the normal flow of the


program. When an exception occurs program execution gets terminated. In such
cases we get a system generated error message. The good thing about
exceptions is that they can be handled in Java. By handling the exceptions we
can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.

TYPES

1. Arithmetic Exception:

2. ArrayIndexOutOfBounds Exception :

3. ClassNotFound Exception :

4. FileNotFound Exception :

5. IO Exception:

6. Interrupted Exception:

7. NoSuchMethod Exception:
CLASS: YAHOO PAGE: 24
PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

8. NullPointer Exception:

9. NumberFormat Exception:

10. StringIndexOutOfBounds Exception:

1. Arithmetic exception:

It is thrown when an exceptional condition has occurred in an arithmetic


operation.

// Java program to demonstrate


// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}

Output:

Can't divide a number by 0


Q.10: What is Multithreading? Explain Thread life cycle with proper
JAVA code?

ANS:

Multithreading in Java

Multithreading in Java is a process of executing multiple threads


simultaneously.

CLASS: YAHOO PAGE: 25


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a


shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There
is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:

1. New

The thread is in new state if you create an instance of Thread class but before
the invocation of start () method.

2. Runnable

The thread is in runnable state after invocation of start () method, but the thread
scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

CLASS: YAHOO PAGE: 26


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

5) Terminated

A thread is in terminated or dead state when its run () method exits.

11. What is Variable? How can we define variables in JAVA? Also list rules
for valid variable names.

ANS:

Variables:

Are used to store information to be referenced and manipulated in a


computer program. They also provide a way of labeling data with a
descriptive name, so our programs can be understood more clearly by the
reader and ourselves. It is helpful to think of variables as containers that
hold information. Their sole purpose is to label and store data in memory.
This data can then be used throughout your program.

Java Variables

A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in


java: local, instance and static.

There are two types of data types in Java primitive and non-primitive.

All Java components require names. Names used for classes, variables, and
methods are called identifiers. In Java, there are several points to remember
about identifiers. They are as follows -
Step 1 − All identifiers should begin with a letter (A to Z or a to z), currency
character ($) or an underscore (_).
Step 2 − after the first character, identifiers can have any combination of
characters.
Step 3 − A keyword cannot be used as an identifier.
Step 4 − Most importantly, identifiers are case sensitive.
Step 5 − Examples of legal identifiers: age, $salary, _value, __1_value.

CLASS: YAHOO PAGE: 27


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Step 6 − Examples of illegal identifiers: 123abc, -salary.

Q.12: Differentiate between constructor and method of class. Define


method overloading and its purpose. Write a program to demonstrate the
constructor overloading.

Differences between Constructors and Methods:

CONSTRUCTORS METHODS

A Method is a collection

A Constructor is a block of of statements which

code that initializes a newly returns a value upon its

created object. execution.

A Constructor can be used to A Method consists of

initialize an object. Java code to be executed.

A Constructor is invoked A Method is invoked by

implicitly by the system. the programmer.

A Constructor is invoked

when a object is created using A Method is invoked

the keyword new. through method calls.

A Constructor doesn‘t have a A Method must have a

CLASS: YAHOO PAGE: 28


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

CONSTRUCTORS METHODS

return type. return type.

A Method does

A Constructor initializes a operations on an already

object that doesn‘t exist. created object.

A Constructor‘s name must

be same as the name of the A Method‘s name can be

class. anything.

A class can have many

A class can have many methods but must not

Constructors but must not have the same

have the same parameters. parameters.

A Constructor cannot be A Method can be

inherited by subclasses. inherited by subclasses.

Three ways to overload a method

In order to overload a method, the argument lists of the methods must differ in
either of these:
1. Number of parameters.
For example: This is a valid case of overloading

CLASS: YAHOO PAGE: 29


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

add (int, int)


add (int, int, int)
2. Data type of parameters.
For example:

add (int, int)


add (int, float)

3. Sequence of Data type of parameters.


For example:

add (int, float)


add (float, int)

Invalid case of method overloading:

When I say argument list, I am not talking about return type of the method, for
example if two methods have same name, same parameters and have different
return type, then this is not a valid method overloading example. This will
throw compilation error.

int add (int, int)


float add(int, int)

Method overloading is an example of Static Polymorphism. We will


discuss polymorphism and types of it in a separate tutorial.

Points to Note:

1. Static Polymorphism is also known as compile time binding or early binding.


2. Static binding happens at compile time. Method overloading is an example of
static binding where binding of method call to its definition happens at Compile
time.

CLASS: YAHOO PAGE: 30


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Constructor Overloading Example

Here we are creating two objects of class Student Data. One is with default
constructor and another one using parameterized constructor. Both the
constructors have different initialization code; similarly you can create any
number of constructors with different-2 initialization codes for different-2
purposes.

Example : Constructor

Class Main {
private String name;

// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
System.out.println ("The name is " + obj.name);
}
}

Output:

Constructor Called:
The name is Programiz

Q.13: Declare a class called employee having employee_id and


employee_name as members. Extend class employees to have a subclass
called salary having designation and monthly_salary as members. Define
following: -Required constructors -A method to find and display all details
of employees drawing salary more than Rs. 20000/-. -Method main for

CLASS: YAHOO PAGE: 31


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

creating an array for storing these details given as command line


arguments and showing usage of above methods.

class Employee
{
String[] employee_id;
String[] employee_name;
}

class Salary extends Employee


{
String[] Designation;
double[] monthly_salary;

Salary(int j)
{
/*initialization of array */

employee_name=new String[j];
employee_id=new String[j];
Designation=new String[j];
monthly_salary= new double[j];

void display(int j)
{

System.out.println("---------------------------------------------------------------");
System.out.println("---------------------------------------------------------------");
System.out.println("\t Details of employee who have salary above 20000");
System.out.println("---------------------------------------------------------------");
System.out.println("---------------------------------------------------------------\n
\n");

System.out.format("%-15s %-15s %-25s %-10s %n","employee


id","employee name","employee Designation","Monthly Salary");
System.out.println("----------------------------------------------------------------------
------");
CLASS: YAHOO PAGE: 32
PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

for(int i=0;i<j;i++)
{

if(monthly_salary[i]>=20000)
{
System.out.format("%-15s %-15s %-25s %-10s
%n",employee_id[i],employee_name[i],Designation[i],monthly_salary[i]);

}
}
}

public static void main(String [] args)


{
Scanner jaimin=new Scanner(System.in);
int length=args.length;

Salary obj = new Salary(length);

if(length==0)
{
System.out.println("please enter employee id");
}

for(int i=0;i<length;i++)
{
obj.employee_id[i]=args[i];

System.out.println("\n\n enter the details of \""+args[i]+"\" employee id");

System.out.print("\n name of employee -->");


obj.employee_name[i]=jaimin.next();

System.out.print("\n Designation of employee -->");


obj.Designation[i]=jaimin.next();

System.out.print("\nMonthly salary of employee -->");


obj.monthly_salary[i]=jaimin.nextDouble();

CLASS: YAHOO PAGE: 33


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

obj.display(length);
}
}

output:

Q.14: Describe an abstract class called Shape which has three subclasses
say Triangle, Rectangle, and Circle. Define one method area () in the
abstract class and override this area () in these three subclasses to calculate
for specific objects i.e. area () of Triangle subclass should calculate area of
triangle etc. Same for, Rectangle, and Circle.

AIM: Describe abstract class called Shape which has three subclasses say
Triangle, Rectangle, Circle. Define one method area () in the abstract class and
override this area() in these three subclasses to calculate for specific object i.e.
area() of Triangle subclass should calculate area of triangle etc. Same for
Rectangle and Circle.

abstract class Shape


{
CLASS: YAHOO PAGE: 34
PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

float dim1,dim2,radius;
abstract float area();
}
class Triangle extends Shape
{
Triangle(float d1, float d2)
{
dim1=d1;
dim2=d2;
}
float area()
{
System.out.println("Area of Triangle is ");
return (dim1*dim2)/2;
}
}
class Rectangle extends Shape
{
Rectangle(float d1, float d2)
{
dim1=d1;
dim2=d2;
}
float area()
{
System.out.println("Area of Rectangle is ");
return dim1*dim2;
}
}
class Circle extends Shape
{
Circle(float d1)
{
radius=d1;
}
float area()
{
System.out.println("Area of Circle is ");
return 3.14f*radius*radius;
}
}
class AbstractClassEx
{

CLASS: YAHOO PAGE: 35


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

public static void main(String arg[])


{
Triangle t=new Triangle(4.3f,5.3f);
Rectangle r=new Rectangle(2.4f,4.2f);
Circle c=new Circle(10.5f);

System.out.println (t.area());
System.out.println (r.area());
System.out.println (c.area());

}
}

Output:

Q.15: Explain inner class and working of concatenation operator + by


giving examples.

Inner class in java


Inner class means one class which is a member of another class. There are
basically four types of inner classes in java.
1) Nested Inner class
2) Method Local inner classes

CLASS: YAHOO PAGE: 36


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

3) Anonymous inner classes


4) Static nested classes
Nested Inner class can access any private instance variable of outer class. Like
any other instance variable, we can have access modifier private, protected,
public and default modifier.
Like class, interface can also be nested and can have access specifiers.
Following example demonstrates a nested class.

class Outer {

// Simple nested inner class

class Inner {

public void show() {

System.out.println("In a nested class method");

class Main {

public static void main(String[] args) {

Outer.Inner in = new Outer().new Inner();

in.show();

Output:
In a nested class method

Method Local inner classes:

CLASS: YAHOO PAGE: 37


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Inner class can be declared within a method of an outer class. In the following
example, Inner is an inner class in outerMethod().

class Outer {

void outerMethod() {

System.out.println("inside outerMethod");

// Inner class is local to outerMethod()

class Inner {

void innerMethod() {

System.out.println("inside innerMethod");

Inner y = new Inner();

y.innerMethod();

class MethodDemo {

public static void main(String[] args) {

Outer x = new Outer();

x.outerMethod();

Output:
Inside outerMethod
Inside innerMethod
.

CLASS: YAHOO PAGE: 38


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Static nested classes

Static nested classes are not technically an inner class. They are like a static
member of outer class.

class Outer {

private static void outerMethod() {

System.out.println("inside outerMethod");

// A static inner class

static class Inner {

public static void main(String[] args) {

System.out.println("inside inner class Method");

outerMethod();

Output:
inside inner class Method
inside outerMethod

Anonymous inner classes

Anonymous inner classes are declared without any name at all. They are created
in two ways.

CLASS: YAHOO PAGE: 39


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

class Demo {

void show() {

System.out.println("i am in show method of super class");

class Flavor1Demo {

// An anonymous class with Demo as base class

static Demo d = new Demo() {

void show() {

super.show();

System.out.println("i am in Flavor1Demo class");

};

public static void main(String[] args){

d.show();

Output:
i am in show method of super class
i am in Flavor1Demo class

Q.16: Explain inheritance with its types and examples.

ANS:

CLASS: YAHOO PAGE: 40


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.

CLASS: YAHOO PAGE: 41


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.

1. class Animal{
2. void eat(){System.out.println ("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

Barking...
Eating...

CLASS: YAHOO PAGE: 42


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As


you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.

1. class Animal{
2. Void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. Void bark () {System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. Void weep () {System.out.println ("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example

We are writing the program where class B, C and D extends class A.

class A
{
public void methodA()
{
System.out.println ("method of Class A");
}
}
class B extends A
{
public void methodB()

CLASS: YAHOO PAGE: 43


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

{
System.out.println ("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println ("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println ("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B ();
C obj2 = new C ();
D obj3 = new D ();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA ();
}
}
Output:

method of Class A
method of Class A
method of Class A

Hybrid Inheritance Example

Program: This example is just to demonstrate the hybrid inheritance in Java.


Although this example is meaningless, you would be able to see that how we
have implemented two types of inheritance(single and hierarchical) together to
CLASS: YAHOO PAGE: 44
PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

form hybrid inheritance.


Class A and B extends class C → Hierarchical inheritance
Class D extends class A → Single inheritance

class C
{
public void disp()
{
System.out.println ("C");
}
}

class A extends C
{
public void disp()
{
System.out.println ("A");
}
}

class B extends C
{
public void disp()
{
System.out.println("B");
}

class D extends A
{
public void disp()
{
System.out.println ("D");
}
public static void main(String args[]){

D obj = new D ();


obj.disp();
}
}
Output:

CLASS: YAHOO PAGE: 45


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Multiple Inheritance
Multiple Inheritance is a feature of object oriented concept, where a class can
inherit properties of more than one parent class. The problem occurs when there
exist methods with same signature in both the super classes and subclass. On
calling the method, the compiler cannot determine which class method to be
called and even on calling which class method gets the priority.

// First Parent class

class Parent1

void fun()

System.out.println("Parent1");

// Second Parent Class

class Parent2

void fun()

System.out.println("Parent2");

CLASS: YAHOO PAGE: 46


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

// Error : Test is inheriting from multiple

// classes

class Test extends Parent1, Parent2

public static void main(String args[])

Test t = new Test();

t.fun();

Output :
Compiler Error

Q.17: What is Wrapper class in Java? Explain with examples

ANS:

A Wrapper class is a class whose object wraps or contains primitive data types.
When we create an object to a wrapper class, it contains a field and in this field,
we can store primitive data types. In other words, we can wrap a primitive value
into a wrapper class object.

Wrapper class Example: Primitive to Wrapper

//Java program to convert primitive into objects


//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly

CLASS: YAHOO PAGE: 47


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

Integer j=a;
//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


}}

Output:

20 20 20

Q.18: What is Exception? Explain various Built-in exceptions in java. Also


give difference between throw and throw keywords.

ANS:

Exception:

In computing and computer programming, exception handling is the process of


responding to the occurrence of exceptions – anomalous or exceptional
conditions requiring special processing - during the execution of a program. In
general, an exception breaks the normal flow of execution and executes a pre-
registered exception handler; the details of how this is done depend on whether
it is a hardware or software exception and how the software exception is
implemented.

An exception (or exceptional event) is a problem that arises during the


execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or
the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner.
Difference between throw and throws in Java

CLASS: YAHOO PAGE: 48


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

No. throw throws

1) Java throw keyword is used Java throws keyword is used to


to explicitly throw an declare an exception.
exception.

2) Checked exception cannot Checked exception can be propagated


be propagated using throw with throws.
only.

3) Throw is followed by an Throws is followed by class.


instance.

4) Throw is used within the Throws is used with the method


method. signature.

5) You cannot throw multiple You can declare multiple exceptions


exceptions. e.g.
public void method() throws
IOException,SQLException.

Q.19: Write a program to create two threads, one thread will print odd
numbers and the second thread will print even numbers between 1 to 100
numbers.

ANS:

class JavaExample {
public static void main(String args[]) {
int n = 100;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {

CLASS: YAHOO PAGE: 49


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

//if number%2 == 0 it means it‘s an even number


if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}

Output:

Even Numbers from 1 to 100 are: 2 4 6 8 10 12 14 16 18 20 22 24 26 28


30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76
78 80 82 84 86 88 90 92 94 96 98 100

Q.20: Declare a class called author having author_name as a private


datamember. Extend author class to have two sub classes called
book_publication & paper_publication.Each of these classes have private
member called title. Show usage of dynamic method dispatch (dynamic
polymorphism) to display book or paper publications of a given author.
Use command line arguments for inputting data.

ANS:

class book
{
private String[] author_name = {"jaimin","naitik"};

void display()
{
for(int i=0;i<author_name.length;i++)
{
System.out.println("Author names --> \t"+author_name[i]);
}
}
}

class book_publication extends book


{

CLASS: YAHOO PAGE: 50


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

private String[][] title = {{"java","c lang","oopc"},{"os","microprocessor


8085","microprocessor 8086"}};

void display(int j)
{
System.out.println("Books name of given author are....");
System.out.println("------------------------------------------------");
for(int i=0;i<3;i++)
{
System.out.println(title[j][i]);
}
}
}

class paper_publication extends book


{
private String[][] title ={{"Atul","Easy paper Solution"},{"Gala paper
Solution","alpha paper Solution"}};

void display(int j)
{
System.out.println("paper publication name of given author are....");
System.out.println("------------------------------------------------");

for(int i=0;i<2;i++)
{
System.out.println(title[j][i]);
}
}
}

class publication
{
public static void main(String [] args)
{
Scanner jaimin = new Scanner(System.in);
book o=new book();
book_publication b_o=new book_publication();
paper_publication p_o=new paper_publication();

int length=args.length;
int author=0,choice;

CLASS: YAHOO PAGE: 51


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

if(length==0)
{
System.out.println("please enter author name");
}

if(length>=2)
{
System.out.println("Add only one name to search names");
}

if(args[0].equals("jaimin"))
{
author=0;
}
else if(args[0].equals("naitik"))
{
author=1;
}
else
{
System.out.println("You have added wrong name of author");
System.exit(-1);
}

System.out.println("press \"1\" to display book author names\npress \"2\" to


display book title names\npress \"3\" to display paper publication names ");
choice=jaimin.nextInt();

switch(choice)
{
case 1:
o.display();
break;

case 2:
b_o.display(author);
break;

case 3:
p_o.display(author);
break;

CLASS: YAHOO PAGE: 52


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

default:
System.out.println("wrong choice....");
System.exit(-2);
break;

}
}

output:

CLASS: YAHOO PAGE: 53


PROGRAMMING WITH JAVA NAME: HARMISH VIRADIYA
ENROLLMENT NO:

CLASS: YAHOO PAGE: 54

You might also like