- Information
- AI Chat
JAVA Internals - Important questions to practice
Data mining (ETEC-677)
Recommended for you
Preview text
Object oriented programming system (oops)
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Java OOPs Concepts
Object
Any entity that has state and behavior is known as an object
An Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory. Objects can communicate without knowing
the details of each other’s data or code.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn’t consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don’t know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
2) Constructor overloading.
In Java, we can overload constructors like methods. The constructor overloading
can be defined as the concept of having more than one constructor with different
parameters so that every constructor can perform a different task.
Consider the following Java program, in which we have used different constructors
in the class.
Example
}
Output:
This a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Id : 10
Student Name : David
In the above example, the Student class constructor is overloaded with two
different constructors, I., default and parameterized.
Here, we need to understand the purpose of constructor overloading. Sometimes,
we need to use multiple constructors to initialize the different values of the class.
3)string classes:
String is a sequence of characters. But in Java, string is an object that represents
a sequence of characters. The java.lang class is used to create a string
object.
There are two ways to create String object:
By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s=”welcome”;
If the string doesn’t exist in the pool, a new string instance is created and placed
in the pool. For example:
String s1=”Welcome”;
String s2=”Welcome”;//It doesn’t create a new instance
2) By new keyword
String s=new String(“Welcome”);//creates two objects and one reference variable
Java String Example
StringExample
Public class StringExample{
Public static void main(String args[]){
String s1=”java”;//creating string by Java string literal
Char ch[]={‘s’,’t’,’r’,’I’,’n’,’g’,’s’};
String s2=new String(ch);//converting char array to string
String s3=new String(“example”);//creating Java string by new keyword
System.out(s1);
System.out(s2);
System.out(s3);
}}
8 static String join(CharSequence delimiter, CharSequence... elements) It
returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? Extends
CharSequence> elements) It returns a joined string.
10 boolean equals(Object another) It checks the equality of string with
the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the
specified char value.
14 String replace(CharSequence old, CharSequence new) It replaces all
occurrences of the specified CharSequence.
15 static String equalsIgnoreCase(String another) It compares another
string. It doesn’t check case.
16 String[] split(String regex) It returns a split string matching regex.
17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
21 int indexOf(String substring) It returns the specified substring index.
22 int indexOf(String substring, int fromIndex) It returns the specified
substring index starting with given index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase using
specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase using
specified locale.
27 String trim() It removes beginning and ending spaces of this string.
28 static String valueOf(int value) It converts given type into string. It is an
overloaded method.
4)JDBC connectivity.
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database. There are
four types of JDBC drivers:
JDBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
Java Database Connectivity Steps
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get
all the records of a table.
Syntax of executeQuery() method
Public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt(“select * from emp”);
While(rs()){
System.out(rs(1)+” “+rs(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method:
Public void close()throws SQLException
Example to close connection
Con();
5) Inheritance
Inheritance 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).
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class.
Terms used in Inheritance Class: A class is a group of objects which have common properties. It is atemplate or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class. The syntax of Java Inheritance Class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derivesfrom an existing class.
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 throughinterface only. We will learn about interfaces later.
Type of inheritance in Java Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. Single Inheritance Example
}
Class Dog extends Animal{ Void bark(){System.out(“barking...”);} } Class BabyDog extends Dog{ Void weep(){System.out(“weeping...”);} } Class TestInheritance2{ Public static void main(String args[]){ BabyDog d=new BabyDog(); d(); d(); d(); }} Output: Weeping... Barking... Eating... Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as hierarchicalinheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. Class Animal{ Void eat(){System.out(“eating...”);}
}
Class Dog extends Animal{ Void bark(){System.out(“barking...”);} } Class Cat extends Animal{ Void meow(){System.out(“meowing...”);} } Class TestInheritance3{ Public static void main(String args[]){ Cat c=new Cat(); c(); c(); c();C.T }}
output: Meowing... Eating...
7)Define servlet? Servlet is a technology which is used to create a web application. Servlet is an API that provides many interfaces and classes includingdocumentation.
- Init method is invoked The web container calls the init method only once after creating the servletinstance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet interface. Syntax of the init method is given below: Public void init(ServletConfig config) throws ServletException
- Service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, itcalls the service method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below: Public void service(ServletRequest request, ServletResponse response) Throws ServletException, IOException 5) Destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up anyresource for example memory, thread etc.
The syntax of the destroy method of the Servlet interface is given below: Public void destroy() 9) Servlet creation to store the data in database. First, create an employee table in Oracle and insert some data as below. Create table employee(empid varchar(10),empname varchar(10),sal int)
Insert into employee values(‘e001’,’raj’,10000) Insert into employee values(‘e002’,’harry’,20000)
Insert into employee values(‘e003’,’sunil’,30000) Insert into employee values(‘e004’,’pollock’,40000) Insert into employee values(‘e005’,’jonty’,50000) Insert into employee values(‘e006’,’kallis’,60000) Insert into employee values(‘e007’,’richard’,70000) Program to display data from database through servlet and JDBC Import java.; Import javax.; Import javax.servlet.; Import java.;
Public class display extends HttpServlet { Public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { PrintWriter out = res(); Res(“text/html”); Out(“<html><body>”); Try { Class(“sun.jdbc.odbc”);
DriverManager(“jdbc:odbc:mydsn”, “system”, “pintu”);Connection con =
}
Compile Javac -cp servlet-api display Running the servlet in a web browser http://localhost:8081/javaservlet/display 10)Method Overloading in Java If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. Ifmethods increases the readability of the program. we have to perform only one operation, having same name of the
Advantage of method overloading Method overloading increases the readability of the program. Different ways to overload the method There are two ways to overload the method in java. By changing number of arguments By changing the data type 1) Overloading: changing no. of arguments In this example, we have created two methods, first add() method performs addition of two numbers and second add method performsaddition of three numbers. In this, we are creating static methods so that we don’t need to createinstance for calling methods.
Class Adder{
Static int add(int a,int b){return a+b;} Static int add(int a,int b,int c){return a+b+c;} } Class TestOverloading1{ Public static void main(String[] args){ System.out(Adder(11,11)); System.out(Adder(11,11,11)); }} Output: 22 33
2)Method Overloading: changing data type of arguments In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and secondadd method receives two double arguments.
Class Adder{ Static int add(int a, int b){return a+b;} Static double add(double a, double b){return a+b;} } Class TestOverloading2{ Public static void main(String[] args){ System.out(Adder(11,11));
JAVA Internals - Important questions to practice
Course: Data mining (ETEC-677)
University: Guru Nanak College of Arts, Science and Commerce
- Discover more from: