3,4,5.2 Java PDF
3,4,5.2 Java PDF
Inheritance
1. what is inheritance? Explain types of inheritance.
A. Inheritance: The mechanism of deriving a new class from old class is called inheritance.
The old class is called as super class/ Base class or parent class.
/*Inheritance*/
Super/
Parent .
Sub /
The inheritance allows sub classes to inherit, the all variables and methods of their parent class.
The Inheritance concept is used to reuse the variables and methods of class.
The inheritance allows the reusability of variables and methods of the class.
Variable declaration;
Method declaration;
In the above syntax subclass name, superclass name are java valid identifiers.
The subclass will contain its own variables and methods as well as variables methods of
superclass.
In the inheritance we can add more properties to a Existing class without modifying class.
Types of inheritance:-
1. Single inheritance.
2. Multiple-inheritance.
3. Multi-level inheritance
4. Hierarchical inheritance.
Single inheritance:-
The process of deriving the only one super(new) class from one base class is called single
inheritance.
In the single Inheritance only one Super class and one sub Class.
Syntax:-
/*single inheritance*/
Variable declaration;
Method declaration;
Variable declaration;
Method declaration;
Example:-
Class A
Variable declaration;
Method declaration;
Class B extends A
Variable declaration;
Method declaration;
Description:-
In the above Syntax sub class name and superclass name of Java valid identifiers.
Multiple Inheritance:-
The process of deriving the new class from more than one old class is known as multiple
inheritance. super [A] [B] super
Multilevel -inheritance:-
The process of deriving the new classes from old class is called multilevel inheritance.
Syntax :-
Class A
Variable Declaration;
Method declaration;
Class B extends A
Variable declaration
Method declaration;
Class C extends B
Variable declaration;
Method declaration;
Hierarchical inheritance:-
The process of deriving more than one a new class from one old class is called hierarchical
inheritance. [A]
Syntax:-
/*Hierarchical Inheritance*/.
Class A
Variable declaration;
Method declaration;
Class B extends A
Variable declaration;
Method declaration;
Class C extends A
Variable declaration;
Method declaration;
Variable declaration;
Method declaration;
Description:-
Subclass constructor:-
1. The sub class constructor is used to initialize (construct) instance variables of both super and
subclasses.
2. The class constructor uses keyword super constructor method of the super class.
II. Call the superclass constructor must be appear as first statement with in subclass
constructor.
III. The parameter list in the super call must match the order and type of instance variable
decrease in the superclass.
A. Method overriding:-
2. Defining a method in the supplies they method having the same name same parameters list
under same return data type as same method in super class.
3. When that the super method is called a method defined in the subclass is called and
executed instead of superclass method this is called overriding.
import java.io.*;
class A
int x;
A(int p)
x=p;
void display()
System.out.println("super"+x);
class B extends A
int y;
B(int p,int q)
super(p);
y=q;
void display()
System.out.println("superclass"+y);
class c
B b1=new B(10,20);
b1.display();
A. Final:-
1. Final is a keyword.
2. Final is a modifier, It is the used to declare the variables methods and classes.
3. The variables methods and classes are declared by using final keyword is called the final
variables final method and the final classes respectively.
Final variables:-
3. The members of the superclass and subclass can be declared using final ”keyword”.
Syntax:-
Final method:-
1. Final methods are methods that are not-override by the methods of the subclass.
Final class:-
Syntax:-
Finalclass Classname
Variable declaration;
Method declaration;
A. Abstract:-
1 Abstract is a keyword.
Abstract method:-1. The method is declared without body using abstract keyword is called
Abstract method.
3. We can indicate that an abstract method must always be a different in the supplies making
overriding is compulsory is done using the keyword abstract.
Syntax:
Abstract class:-
Syntax:-
Variable declaration;
Non-abstract method;
Abstract method;
Eg:
Int a,b;
Void display();
Interface
1.Explain about interface .(or)How to implement interface in java.
A. Interface:-
4. These abstract methods do not specify any code to implement that variables &methods
contains only constants.
Defining An interface:-
Syntax:-
Interface interfacename
Variable declaration;
Method declaration;
In the above syntax , interface is a keyword and interface name is any java valid identifier.
Syntax:
Method declaration:-
Interface area
Extending interface:-
The new sub interfaces will inherit all the properties of super interface. This is done by using
an “extends” keyword.
Syntax:-
Eg; interface A
Interface B extends A
{
RAJA (CS DEPARTMENT), ADITYA DEGREE COLLEGE Page 12
Float compute (float x, floaty);
}.
Implementing interface:-
Interface are used as super class , whose properties are inherited by class.
Syntax:-
Body of class;
Example :-
Return(x*y);
Interface can be used to declare a set of constants that can be used in different classes.
Example program:-
Interface area
Return(x*y);
Return(pi*x*y);
Class inter
area ar;
ar=rect;
ar=cir;
Output:
Javac inter.Java
Java inter4
3.2
A .Array:- An array is a variable that can store multiple values of same data type where as an
ordinary data variable can store a single value at a time.
Types of arrays:-
Dimensional array:-
1.An array in which list of elements are stored in a continuous memory locations and access
only one subscript.
Declaration of I D array:
Syntax: -
Type arrayname[ ];
Or
Type [ ] arrayname;
After declaring an array we need to create it in the memory Java allows us to create arrays
using new operator only.
Syntax:-
Syntax:-
Initialization of 1D array:
Example:
In the above example five elements are stored in array a the array element are stored in
continuous memory locations.
*a[3] =6
a [4]= 1.
5 4 2 6 1
Array length:-
Java we can find the length of the array “a” using “a .length”.
Example:-
Int n=a.length
For (i=0;i<n;i++)
System.out.println(“ ”+ a[] );
An array in which list of elements are stored in same rows and columns and accessed by using
two subscripts.
Declaration:
Syntax:-
Or
type [ ] [ ] arrayname;
Here, type is a data type array name is the name of the array .Remember we do not have the
size of the error in the declaration.
After declaring an array we need to create it in the memory Java allows us to create arrays
using “new” operator only.
Syntax:-
Example
Initialization of a 2D array:-
Syntax :-
Type arrayname [ ] [ ] = {list of values of 1 st array}, {list of values of 2nd row },…{list of values of
last row};
EXAMPLE;-
Int a [ ] [ ]= 5,6,3,2,4
Subscripts can also reflected in for loops that the array elements.
Example :
For
System.out.println(“ ”+a[i][j]);
Strings
1 .Explain about strings in java (or) what is string? Write about various string
methods in Java.
A String:- String represents sequence characters in Java, strings are class objects and
implemented using two classes namely “string & string buffer”.
A java string is an initialized of the string class”. A java string is not a character array and is not
terminated with null.
Syntax -1:
String Stringname;
Eg: string a;
Eg:
A=new string(“Hari”);
Syntax
Eg;
It is possible to get the length of string using the “length method ” of the stirng class
Int m = a legth();
String array : we can also create and use arrays that contain strings.
Syntax :
String method.
The string class defines a number of methods that allows us to perform a variety of string
manipulation tasks.
Case
String buffer class is similar to string class while string creates strings of fixed length,
We can insert character in the middle of the string are appeared string at the end.
Syntax :
A.Vector:-
Syntax:-
insert element :- it is used to add the specified item at nth position to the vector at the end.
Element At(n):-
size:-
Eg :- V.size();
It is used to remove the element stored in the nth position of the vector .
Copy into:-
Advantages;-
2 a vector can be used to store a list of objects that may vary in size.
3 we can add and delete objects from the list as and when required.
The major constraint in using vectors is that we cannot directly store simple data type in
your data we can only store objects therefore we need to convert simple data type to objects
A .Vectors cannot handle primitive data types like int ,float ,long, char and double. primitive
data types may be converted into objects types by using wrapper class. Wrapper classes
Boolean Boolean
RAJA (CS DEPARTMENT), ADITYA DEGREE COLLEGE Page 22
Char Character
Double Double
Float Float
Int Integer
long Long:-
Unit -4
A. Errors:-
An Error may produce an incorrect output or may terminate the executive of the
1. Compile time.
2. Run time.
Compile time:-
All Syntax errors will detect and therefore these errors are known as compile time errors
Whenever the company displays an error it will not create the class file Java compiler does a
Nice job of telling us where the errors are in the program most of the compile time errors are
(compile time)
class error
Void get()
X=10;
Y=20;
Runtime errors:- A program may compile successfully creating the class file but may not run
properly such programs may produce of wrong results due to wrong logic.
(Runtime)
Class error
Int x, y;
Y=0;
System.out.println(“c”+c);
exception.
A . Exception :-an exception is an event that occurs during the execution of program that
disturbs in a normal flow of execution when an error occur within a method the method
creates an object called an “Exception object” contents information about the error including
creating an exhibition object and handling it to the runtime system is called throwing an
exception.
Try
Exception handling:-
That
thrown Contains
Statements an
Try block
Catch
That causes
Statements
Or catch
block
If the exception object is not caught and handled properly , the interpreter will display error
Message and will terminate the program. If we want the program to continue with execution of
remaining code then we should try to catch the exception object thrown by the error
Synatx:-
Try
Java uses as keyword “try”. To preface a block of code i.e likely to cause an error condition and
throw an exception.
Catch catches the exception thrown by the try block and handles it approximately. The catch
Class error 1
Int a= 10;
Int b= 5;
Int c= 5;
Int x,y;
Try
X= a/(b.c);
Catch(Automatic exception e)
System.out.println(“Division by zero”);
Y= a/(b+c);
System.out.println(“y=”+y);
Output:-
Division by zero.
1 Checked exception:-
Java.lang.exception class.
2 Unchecked exceptions:-
These exceptions are not handled in the program but the JVM handles such exceptions. These
4 Out of memory Exception Caused when there is no enough memory to allocate new
object
5 Null Pointer Exception Caused by referring a null object
Syntax:-
Statements;
Catch(Exception type 1 e)
Statements;
Catch(Exception – type2 - e)
Statements;
Catch (Exception-type n – e)
Statements;
Process:-
When an expression in a try block is generated, the Java creates the multiple catch
statements like classes in a switch statement.
The first statement whose parameter matches with the exception and remaining
statements will be skipped.
Eg :- program:-
Class example
Int b=5;
Try
Int x=(a1/b-a2);
System.out.println(“Division by zero”);
Sytem.out.println(“wrong data”);
A . Finally statements :- Java supports another statements known as finally sattements that
can be sued to handle an exception that is not catch any of the previous catch statements.
Synatx 1 Sytax 2
Try try
{ {
Statements;
} {
Finally() statements;
{ }
fianlly()
Statements; {
} statements;
4.1
Multi-threaded programming.
1 Write about multithreading program.
A . Multithreading :- where program is divided into two or more sub program which can be
implemented at the same time.
Thread :- It is similar to a program that has a single flow of control has a beginning a body and an end an
executable commands.
Threads in Java subprograms of a main thread and share the same memory space they are known as
light weight thread or “light weight process.”
Create a thread:- Threads are implemented with the form of an object that contained a method called
“run()”. This run() is the heart of the thread.
Syntax:-
Sattements;
The Run() should be invoked by an object of the concern thread the Run() can be executed by using
“start()” method.
Defining a class that extends “thread” class and override its Run method.
Define a class that implements runnable interface the Rebel interface has only one run method that can
be executed by the thread
Syntax:-
Statements;
Eg :-
--------;
t.start();
Stopping a thread
when we want to stop a thread from running state then call “stop method”.
Eg :- t.Stop();
Blocking a thread :-
A thread can also be temporarily suspended or blocked from entering into a runnable are subsequent
running state by using following 3 thread methods.
**If that red is the Block with the weight then thread is invoked by notify
A . Thread :-
It is similar to a program that has a single flow of control has a beginning a body and an end an
executable commands.
3 Blocked state
4 Dead state
New born
Stop()
Dead state
Yield
Running runnable
Stop()
Blocked state
1 New born state:- when we create a thread object born and set to be in newborn
the thread is not scheduled for running at this state we can do. *scheduled it for running using “start()”.
New
born
Runnable Running
state state
The Runnable state means that the thread is ready for execution and is waiting the availability of the
processor if all the Threads have equal priority then they are given time slots for execution in a round
Robin fashion. This process of assigning time to threads is known as “time slicing”.
Yield is means that the current thread is willing to give another thread.
Running state:-
Running statements that the processor has give its time to the trade for its execution around credit
control in one of the following situations.
A) It has been suspended using suspended a suspended thread can be released by using the resume().
Suspend
Thread thread
Notify
Blocked state:-
A thread is said to be blocked when it is prevented from entering into the runnable state and
sequentially the running state. This happens when the thread is suspended are waiting in order to
satisfy the certain requirements.
Dead state:-
A. Thread priority:-
In java is thread is assigned a priority which affects the order in which its scheduled for running.
The thread of same priority are given. Equal treatment by Java scheduler and therefore they shared the
processor on a Round Robin fashion Java permits as to priority of a thread u sing the set priority() is as
follows.
Sytax:-
The int numbers is an integer value to which the threads priority is set. The thread class defines
several priority constants
NORM – PRIORITY= S
MAX – PRIORITY=10
The int numbers may resume one of these constants (or) any value between ‘0’ to ‘10’
The multiple threads are ready for execution the java system chooses the highest priority thread and
execute it.
A. When the thread is blocked with sleep () is enclosed in a try block and followed by a catch
block.
* Java runtime system will throw “illegal thread state exception” whenever we attempt to invoke a
method that a thread cannot handle in the given statement.
*When we call a thread method that is likely to throw an exception handler to catch it.
Catch(Thread Death e)
{
Statements; // Killed thread.
}
Catch (interrupted exception e)
{
Statements; // cannot handle it in the current statement.
Catch (illegal Argument exception e
{
Statements; // Illegal methods)
}
catch( exception e)
{
Statements; // Any other.
}
A . synchronization
One thread main try to read record from a file while another is still waiting for same file.
Depending on the situation Java and able to overcome this problem using a technique known as
synchronization.
In case of Java the keyword synchronized help to solve such problems by keeping a watch on
such locations.
Eg :-
Synchronization void update()
{
Statements; // code here is synchronized.
When we declare a method synchronized. Java creates a “monitor” and hands it over to
the thread that calls the method first time.
Eg:- synchronized (lock object)
{
Statements;
}.
A Runnable Interface declare the run () that is required for implementing threads in your
programs.
2 Implementing Run().
3 Create a thread by defining an object that is initialized from the runnable class as target of the
thread
Eg
import.java.lang.Thread;
Class x implements Runnable // step 1
{
Advantages:-
The classes contained in the packages of other programs can be easily reused.
In the packages classes can be unique two classes in two different packages can have the same
name.
Types of packages:-
5 java.net they include classes for communication with the local computers
as well as internet servers
There are two ways to access classes Store package they are :-
The approach was the fully qualified class name the “fully qualified class name” The fuly
qualified class name consist of Java package name and classname separately by dots
representing different levels.
Process :-
Syntax:-
Eg:- Java.awt.colour;
In the above example “awt” is the package of the Java package and colour is the class of the WT
package.
This approach is just a import statement this statement must be written at the top of the
program it consists of import keyword package name and class name along with dot.
Process:-
Syntax:-
Example:-
1 import Java.out.colour;
packages that are design and understand that by the user are called used at different packages.
Naming action :-
Syntax:-
2 what is user defined package how to create and access user defined package?
package that are designed and created by the user are called user defined
packages
creating a package:-
To create a package must first deploy area package using the package keyword
Declaring a package:-
Synatx:-
Package packagename;
Public class classname;
{
Statements; // body
}
Eg ;- package Student;
Public class Sum
{
Public int add(int x, int y)
{
Return(x+y);
}
}
Steps for creating packages:-
*Creating a sub directory with this name under the directory where main source files are
stored
D:/MCCs/> Cd student
D:/MCCs/student/>edit
Synatx :-
Package packagename;
*The name of the sub directory must be the name of the package exactly.
*Define the class that is to be put in the package and declare it using “public”.
Eg :
package student;
Public class Sum
{
Publc int add(int x, int y)
{
Return(x+y);
}
}
*Save the source file by c;ass name, “sum.java”.
*Switch to sub directory created earlier and compile the source file when completed, the
package contain “sum.class file” of the source file.
The import statement is used to use t=a package . The general form of using package is
Syntax
Eg : import student.sum;
Here , student id the name of the package and sum is the name of the class in it.
Eg :-
Import student.Sum;
Calss Test
{
Public static void main(String args )
{
Sum s= new Sum()””;
Int n=S.add(2,3);
System.out.println(“sum is”+n);
suppose we want to add another class Sab to the student package then follow the steps
Eg:
package student ;
Public class Sub
{
Public int Sub(int x , int y)
Return(x-y);
}
}
*compare Sab dot Java file. this will create a subclass file under place it in the directory student
Hiding classes:-
When we import packages using “*” all public classes are imported.
If we want to hide a particular class we must not use “public” in the class definition
Syntax:-
Package packagename;
Public class classname1
{
Body of the classname1;
}
Class classname2
{
Body of the classname2;
Eg :-
Package p1;
Public class A
{
Public void dislay()
{
System.outprintln(“This is a class B”);
}
}
Static import:-
This feature eliminates the need of qualifying a static member with class name static import
declaration is similar to that of import .
We can use the import statement to import class .From packages and use them without
qualifying the package.
Similarly, we can use the static import statement to import static members from classes and
use them without qualifying the class name
Eg :-
Import static java.lang.math.*;
Public class math op
{
Double area = pi*r*r;
Sytem.out.println(“Area”+area);
}
Public static void main (String args[])
{
Mathop obj = new mathop;
Obj.circle(2,3);
}
}