programming in java
programming in java
ENROLLMENT NO:
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.
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 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.
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
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
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.
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
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Suggestion: If you are beginner to java, lookup only three usage of this
keyword.
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
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.
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.
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.
ANS:
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
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:
if (n % i == 0) {
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.
Java provides four types of access specify that we can use with classes and other
entities.
These are:
#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.
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.
class Main
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.
class A
System.out.println ("SoftwareTestingHelp!!");
class Main
obj.display();
Output:
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.
Class A
System.out.println ("SoftwareTestingHelp");
class B extends A {}
class C extends B {}
class Main{
Output:
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.
class TestClass{
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
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 {
// getter method
return this.strname;
// setter method
this.strname= name;
d.setName("Java Programming");
System.out.println(d.getName());
Output:
ANS:
3) Abstract class can have Interface has only static and final
final, non-final, static and variables.
non-static variables.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Collections in Java
Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.
HashMap Hashtable
ANS:
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'
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"
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"
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,
This method returns a String whose value is the String used to invoke the
method, but with any lowercase characters converted touppercase—for
example,
ANS:
Exception
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:
1. Arithmetic exception:
Output:
ANS:
Multithreading in Java
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.
5) Terminated
11. What is Variable? How can we define variables in JAVA? Also list rules
for valid variable names.
ANS:
Variables:
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.
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.
CONSTRUCTORS METHODS
A Method is a collection
A Constructor is invoked
CONSTRUCTORS METHODS
A Method does
class. anything.
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
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.
Points to Note:
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";
}
Output:
Constructor Called:
The name is Programiz
class Employee
{
String[] employee_id;
String[] employee_name;
}
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");
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]);
}
}
}
if(length==0)
{
System.out.println("please enter employee id");
}
for(int i=0;i<length;i++)
{
obj.employee_id[i]=args[i];
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.
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
{
System.out.println (t.area());
System.out.println (r.area());
System.out.println (c.area());
}
}
Output:
class Outer {
class Inner {
class Main {
in.show();
Output:
In a nested class method
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");
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
y.innerMethod();
class MethodDemo {
x.outerMethod();
Output:
Inside outerMethod
Inside innerMethod
.
Static nested classes are not technically an inner class. They are like a static
member of outer class.
class Outer {
System.out.println("inside outerMethod");
outerMethod();
Output:
inside inner class Method
inside outerMethod
Anonymous inner classes are declared without any name at all. They are created
in two ways.
class Demo {
void show() {
class Flavor1Demo {
void show() {
super.show();
};
d.show();
Output:
i am in show method of super class
i am in Flavor1Demo class
ANS:
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
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...
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...
class A
{
public void methodA()
{
System.out.println ("method of Class A");
}
}
class B extends A
{
public void methodB()
{
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
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[]){
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.
class Parent1
void fun()
System.out.println("Parent1");
class Parent2
void fun()
System.out.println("Parent2");
// classes
t.fun();
Output :
Compiler Error
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.
Integer j=a;
//autoboxing, now compiler will write Integer.valueOf(a) internally
Output:
20 20 20
ANS:
Exception:
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++) {
Output:
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]);
}
}
}
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]);
}
}
}
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;
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);
}
switch(choice)
{
case 1:
o.display();
break;
case 2:
b_o.display(author);
break;
case 3:
p_o.display(author);
break;
default:
System.out.println("wrong choice....");
System.exit(-2);
break;
}
}
output: