Sie sind auf Seite 1von 29

COLLEGE OF TECHNOLOGY, BHOPAL

DEPARTMENT OF INFORMATION
TECHNOLOGY

LAB MANUAL
Programme

: BE

Semester

:III

Course Code

: Civil-305

Subject Name

: Computer programming(Java)

Prepared By:

Approved By:

Index
S.No.

Contents

1.

Syllabus

2.

List of Experiments /Methods

3.

Viva Questions

4.

Grading Sheet

Page No.

Syllabus
CE- 306 Computer Programming
UNIT-I
Basic Java Features - C++ Vs JAVA, JAVA virtual machine, Constant & Variables, Data
Types, Class, Methods, Objects, Strings and Arrays, Type Casting, Operators, Precedence
relations, Control Statements, Exception Handling, File and Streams, Visibility, Constructors,
Operator and Methods Overloading, Static Members, Inheritance: Polymorphism, Abstract
methods and Classes
UNITII
Java Collective Frame Work - Data Structures: Introduction, Type-Wrapper Classes for
Primitive Types, Dynamic Memory Allocation, Linked List, Stack, Queues, Trees,
Generics: Introduction, Overloading Generic Methods, Generic Classes, Collections: Interface
Collection and Class Collections, Lists, Array List and Iterator, Linked List, Vector.
Collections Algorithms: Algorithm sorts, Algorithm shuffle, Algorithms reverse, fill, copy, max
and min Algorithm binary Search, Algorithms add All, Stack Class of Package java. Util, Class
Priority Queue and Interface Queue, Maps, Properties Class, Un-modifiable Collections.
UNITIII
Advance Java Features - Multithreading: Thread States, Priorities and Thread
Scheduling, Life Cycle of a Thread, Thread Synchronization, Creating and Executing Threads,
Multithreading with GUI, Monitors and Monitor Locks. Networking: Manipulating URLs, Reading
a file on a Web Server, Socket programming, Security and the Network, RMI, Networking,
Accessing Databases with JDBC: Relational Database, SQL, MySQL, Oracle
UNITIV
Advance Java Technologies - Servlets: Overview and Architecture, Setting Up the
Apache Tomcat Server, Handling HTTP get Requests, Deploying a web Application, Multitier
Applications, Using JDBC from a Servlet, Java Server Pages (JSP): Overview, First JSP
Example, Implicit Objects, Scripting, Standard Actions, Directives, Multimedia: Applets and
Application: Loading, Displaying and Scaling Images, Animating a Series of Images, Loading
and playing Audio clips
UNITV
Advance Web/Internet Programming (Overview): J2ME, J2EE, EJB, XML.

References books
1. Deitel & Deitel, JAVA, How to Program; PHI, Pearson.
2. E. Balaguruswamy, Programming In Java; TMH Publications
3. The Complete Reference: Herbert Schildt, TMH
4. Peter Norton, Peter Norton Guide To Java Programming, Techmedia.
5. Merlin Hughes, et al; Java Network Programming , Manning Publications/Prentice Hall

List of Program to be perform (Expandable)


1. Write the importance of object oriented programming. Mention the features of
JAVA

2. Write a program to show Concept of CLASS in JAVA


3. Write a program using if else. Statement
4. Write a program showing use of constructor
5. Write a program to show Type Casting in JAVA
6. Write a program to show How Exception Handling is in JAVA
7. Write a program to show Inheritance
8. Write a program to show Polymorphism
9. Write a program to show Interfacing between two classes
10. Write a program to Add a Class to a Package
11. Write a program to demonstrate AWT.
12. Write a program to Hide a Class
13. Write a program to show Data Base Connectivity Using JAVA
14. Write a program to show HELLO JAVA in Explorer using Applet
15. Write a program to show Connectivity using JDBC
16. Write a program to demonstrate multithreading using Java.
17. Write a program to demonstrate applet life cycle.

1.Write the importance of object oriented programming. Mention the features of JAVA

Java is a programming language created by James Gosling from Sun Microsystems (Sun) in
1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the
steermanship for Java.
Over time new enhanced versions of Java have been released. The current version of Java is
Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform allows
software developers to write program code in other languages than the Java programming
language which still runs on the Java virtual machine. The Java platform is usually
associated with the Java virtual machine and the Java core libraries.
Java has the following properties:

Platform independent: Java programs use the Java virtual machine as abstraction and
do not access the operating system directly. This makes Java programs highly
portable. A Java program (which is standard complaint and follows certain rules) can
run unmodified on all supported platforms, e.g., Windows or Linux.
Object-orientated programming language: Except the primitive data types, all
elements in Java are objects.

Strongly-typed programming language: Java is strongly-typed, e.g., the types of the


used variables must be pre-defined and conversion to other objects is relatively strict,
e.g., must be done in most cases by the programmer.

Interpreted and compiled language: Java source code is transferred into the bytecode
format which does not depend on the target platform. These bytecode instructions will
be interpreted by the Java Virtual machine (JVM). The JVM contains a so called
Hotspot-Compiler which translates performance critical bytecode instructions into
native code instructions.

Automatic memory management: Java manages the memory allocation and deallocation for creating new objects. The program does not have direct access to the
memory. The so-called garbage collector automatically deletes objects to which no
active pointer exists.

2. Write a program to show Concept of CLASS in JAVA


import java.util.*;
public class DateDemo{
public static void main(String[] args) {
Date d=new Date();
System.out.println("Today date is "+ d);
}
}

3.Write a program using SWICTH Statement


import java.io.*;
public class SwitchExample{
public static void main(String[] args) throws Exception{
int x, y;
BufferedReader object = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("Enter two numbers for operation:");
try{
x = Integer.parseInt(object.readLine());
y = Integer.parseInt(object.readLine());
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("enter your choice:");
int a= Integer.parseInt(object.readLine());
switch (a){
case 1:
System.out.println("Enter the number one=" + (x+y));
break;
case 2:
System.out.println("Enter the number two=" + (x-y));
break;
case 3:
System.out.println("Enetr the number three="+ (x*y));
break;
case 4:
System.out.println("Enter the number four="+ (x/y));
break;
default:
System.out.println("Invalid Entry!");
}
}
catch(NumberFormatException ne){
System.out.println(ne.getMessage() + " is not a numeric value.");
System.exit(0);
}
}
}

4.Write a program showing use of constructor


class another{
int x,y;
another(int a, int b){
x = a;
y = b;
}
another(){
}
int area(){
int ar = x*y;
return(ar);
}
}
public class Construct{
public static void main(String[] args)
{
another b = new another();
b.x = 2;
b.y = 3;
System.out.println("Area of rectangle : " + b.area());
System.out.println("Value of y in another class : " + b.y);
another a = new another(1,1);
System.out.println("Area of rectangle : " + a.area());
System.out.println("Value of x in another class : " + a.x);
}
}

5.Write a program to show Type Casting in JAVA


//Integer code1
public class CastExample
{
public static void main(String arg[])
{
String s=27;
int i=Integer.parseInt(s);
System.out.println(i);
Float f=99.7f;
int i1=Integer.parseInt(f);
}
}
//Integer code2
public class CastExample
{
public static void main(String arg[])
{
String s=27;
int i=(int)s;
System.out.println(i);
}
}
//Integer to String
int a=97;
String s=Integer.toString(a);

//Long to String
String s=Long.toString(longvalue);
//Float to String
String s=Float.toString(floatvalue);
//String to Integer
String s=7;
int i=Integer.valueOf(s).intValue();
(or)
int i = Integer.parseInt(s);
//String to Double
double
a=Double.valueOf(s).doubleValue();
//String to Long
long lng=Long.valueOf(s).longValue();
(or)
long lng=Long.parseLong(s);
//String to Float
float f=Float.valueOf(s).floatValue();

(or)
String s=+a;

//Character to Integer
char c=9;
int i=(char)c;

//Double to String
String s=Double.toString(doublevalue);

//String to Character
String s=welcome;
char c=(char)s;

6. Write a program to show How Exception Handling is in JAVA


import java.io.*;
public class exceptionHandle{
public static void main(String[] args) throws Exception{
try{
int a,b;
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()
+ " is not a numeric value.");
System.exit(0);
}
}

7. Program that illustrates inheritance in java using person class


class Person
{
String FirstName;
String LastName;
Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
void Display()
{
System.out.println("First Name : " +
FirstName);
System.out.println("Last Name : " +
LastName);
}}
class Student extends Person
{
int id;
String standard;
String instructor;
Student(String fName, String lName, int nId,
String stnd, String instr)
{
super(fName,lName);
id = nId;
standard = stnd;
instructor = instr;
}
void Display()
{
super.Display();
System.out.println("ID : " + id);
System.out.println("Standard : " +
standard);
System.out.println("Instructor : " +
instructor);
}}
class Teacher extends Person
{

String mainSubject;
int salary;
String type; // Primary or Secondary School
teacher
Teacher(String fName, String lName, String
sub, int slry, String sType)
{
super(fName,lName);
mainSubject = sub;
salary = slry;
type = sType;
}
void Display()
{
super.Display();
System.out.println("Main Subject : " +
mainSubject);
System.out.println("Salary : " + salary);
System.out.println("Type : " + type);
}}
class InheritanceDemo
{
public static void main(String args[])
{
Person pObj = new
Person("Rayan","Miller");
Student sObj = new
Student("Jacob","Smith",1,"1 - B","Roma");
Teacher tObj = new
Teacher("Daniel","Martin","English","6000","Prim
ary Teacher");
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
System.out.println("Teacher :");
tObj.Display();
}
}

8. Polymorpism In Java
class overLoading {
public static void main(String[] args)
{
functionOverload obj = new functionOverload();
obj.add(1,2);
obj.add(\"Life at \", \"?\");
obj.add(11.5, 22.5);
}
}
class functionOverload {
/*
* void add(int a, int b) // 1 - A method with two parameters {
*
* int sum = a + b; System.out.println(\"Sum of a+b is \"+sum);
*
*}
*/
void add(int a, int b, int c)

int sum = a + b + c;
System.out.println(\"Sum of a+b+c is \"+sum);
}
void add(double a, double b)
double sum = a + b;
System.out.println(\"Sum of a+b is \"+sum);
}
void add(String s1, String s2)
{
String s = s1 + s2;
System.out.println(s);
}
}

9.Write a program to show Interfacing between two classes


public interface First {
public void show_first();
}
public interface Second {
public void show_second();
}
public class One {
public void show_one()
{
System.out.println("Class One");
}
}
public class Two extends One implements First, Second{
public void show_first()
{
System.out.println("Interface first");
}
public void show_second()
{
System.out.println("Interface second");
}
public void show_two()
{
System.out.println("Class two");
}
}
public class DemoInterface {
public static void main(String
a[])
{
Two t=new Two();
t.show_first();
t.show_second();
t.show_one();
t.show_two();
}}

10.

Write a program to Add a Class to a Package


1. Package statment (optional).
2. Imports (optional).
3. Class or interface definitions.

// This source file must be Drawing.java in the illustration directory.


package illustration;
import java.awt.*;
public class Drawing {
...
}
Imports: three options
The JOptionPane class is in the swing package, which is located in the javax package. The wildcard character
(*) is used to specify that all classes with that package are available to your program. This is the most
common programming style.
import javax.swing.*; // Make all classes visible altho only one is used.
class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}}Classes can be specified explicitly on import instead of using the wildcard character.
import javax.swing.JOptionPane; // Make a single class visible.
class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}
Alternately we can the fully qualified class name without an import.
class ImportTest {
public static void main(String[] args) {
javax.swing.JOptionPane.showMessageDialog(null, "Hi");
System.exit(0);
}
}

11. Write a program to demonstrate AWT.


Create AWT Button Example
This java example shows how to create a Button using AWT Button class.
*/
import java.applet.Applet;
import java.awt.Button;
/*
<applet code="CreateAWTButtonExample" width=200 height=200>
</applet>
*/
public class CreateAWTButtonExample extends Applet{
public void init(){
/*
* To create a button use
* Button() constructor.
*/
Button button1 = new Button();
/*
* Set button caption or label using
* void setLabel(String text)
* method of AWT Button class.
*/
button1.setLabel("My Button 1");
/*
* To create button with the caption use
* Button(String text) constructor of
* AWT Button class.
*/
Button button2 = new Button("My Button 2");
//add buttons using add method
add(button1);
add(button2);
}
}

12. Write a program to Hide a file


Path path = FileSystems.getDefault().getPath("directory", "hidden.txt");
Boolean hidden = path.getAttribute("dos:hidden", LinkOption.NOFOLLOW_LINKS);
if (hidden != null && !hidden) {
path.setAttribute("dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
}

13. Write a program to show Data Base Connectivity Using JAVA


/STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver";
static final String DB_URL =
"jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to
database...");
conn =
DriverManager.getConnection(DB_URL,U
SER,PASS);
//STEP 4: Execute a query
System.out.println("Creating
statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age
FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

String last = rs.getString("last");


//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
14. Write a program to show HELLO JAVA in Explorer using Applet

Create a Java Source File


Create a file named HelloWorld.java with the Java code shown here:
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
Compile the Source File
If the compilation succeeds, the compiler creates a file named HelloWorld.class in the same directory (folder)
as the Java source file (HelloWorld.java). This class file contains Java bytecodes.
If the compilation fails, make sure you typed in and named the program exactly as shown above. If you can't
find the problem, see Common Compiler and Interpreter Problems.
Create an HTML File that Includes the Applet
Using a text editor, create a file named Hello.html in the same directory that contains HelloWorld.class. This
HTML file should contain the following text:
<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Run the Applet
To run the applet, you need to load the HTML file into an application that can run Java applets. This
application might be a Java-compatible browser or another Java applet viewing program, such as the Applet
Viewer provided in the JDK. To load the HTML file, you usually need to tell the application the URL of the
HTML file you've created. For example, you might enter something like the following into a browser's URL
or Location field:
file:/home/kwalrath/HTML/Hello.html
Once you've successfully completed these steps, you should see something like this in the browser window:

15. Write a program to show Connectivity using JDBC


package com.java2novice.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConnection {
public static void main(String a[]){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.
getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

16. Write a program to demonstrate multithreading using Java.

class MyThread extends Thread


{
public MyThread()
{
super("Using Thread Class");
System.out.println("Child thread : " + this);
start();
}
public void run()
{
try
{
for(int i = 5; i > 0 ; i--)
{
System.out.println("Child Thread " + i );
Thread.sleep(500);
}
}
catch(InterruptedException ie){}
System.out.println("Exiting Child Thread...");
}
}
class TestMyThread
{
public static void main(String args[])
{
MyThread a = new MyThread();
try
{
for(int k=5; k > 0 ; k--)
{
System.out.println("Main Thread " + k);
Thread.sleep(1000);
}
}
catch(InterruptedException ie1){}
System.out.println("Exiting Main Thread...");
}
}

17. Write a program to demonstrate applet life cycle.

Introduction: Applet is java program that can be embedded into HTML pages. Java applets runs on the java
enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client
browser, so there are some restrictions on it. Applet can't access system resources on the local computer.
Applets
are
used
to
make
the
web
site
more
dynamic
and
entertaining.
Advantages of Applet:

Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plugin
Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security
approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning to a web page User
can also have full access to the machine if user allows
Disadvantages of Java Applet:

Java plug-in is required to run applet


Java applet requires JVM so first time it takes significant startup time
If applet is not already cached in the machine, it will be downloaded from internet and will take time
Its difficult to desing and build good user interface in applets compared to HTML technology All these
methods are optional

Life cycle of applet is governed by browser. There are 5 methods in the life cycle of an applet All these
methods are optional
init( ) : Called when the applet is first created, to perform first-time
initialization of the applet
start( ): Called every time the applet moves into sight on the Web browser, to allow the applet to start up its
normal operations (especially those that are shut off by stop( )). Also called after init( ).
paint( ) : Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to
perform special painting on the canvas of an applet.
stop( ) : Called every time the applet moves out of sight on the Web browser, to allow the applet to shut off
expensive operations. Also called right before destroy( ).
destroy( ): Called when the applet is being unloaded from the page, to perform final release of resources
when the applet is no longer used
Detailed Explanation:
init () method: The life cycle of an applet is begin on that time when the applet is first loaded into the
browser and called the init() method. The init() method is called only one time in the life cycle on an applet.
The init() method is basically called to read the PARAM tag in the html file. The init () method retrieve the
passed parameter through the PARAM tag of html file using get Parameter() method All the initialization such
as initialization of variables and the objects like image, sound file are loaded in the init () method .After the
initialization of the init() method user can interact with the Applet and mostly applet contains the init()
method.
Start () method: The start method of an applet is called after the initialization method init(). This method

may be called multiples time when the Applet needs to be started or restarted. For Example if the user wants
to return to the Applet, in this situation the start Method() of an Applet will be called by the web browser and
the user will be back on the applet. In the start method user can interact within the applet.
Stop () method: The stop() method can be called multiple times in the life cycle of applet like the start ()
method. Or should be called at least one time. There is only miner difference between the start() method and
stop () method. For example the stop() method is called by the web browser on that time When the user leaves
one applet to go another applet and the start() method is called on that time when the user wants to go back
into the first program or Applet.
destroy() method: The destroy() method is called only one time in the life cycle of Applet like init() method.
This method is called only on that time when the browser needs to Shut down.
Run this applet and view the messages in the console window.
import java.awt.*;
import java.applet.Applet;
public class LifeCycle extends Applet
{
public void init()
{
showStatus("This is Init");
for(int i=0;i<100000000;i++);
}
public void start()
{
showStatus("This is Start");
for(int i=0;i<100000000;i++);
}
public void paint(Graphics g)
{
showStatus("This is Paint");
for(int i=0;i<1000000;i++);
}
public void stop()

{
showStatus("This is Stop");
for(int i=0;i<1000000;i++);
}
public void destroy()
{
showStatus("This is Destroy");
for(int i=0;i<1000000;i++);
}
}
/*

VIVA QUESTIONS

Q:1 What do you know about Java?


A: Java is a high-level programming language originally developed by Sun Microsystems and released in
1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
Q: 2 What are the supported platforms by Java Programming Language?
A: Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux
like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.
Q: 3 List any five features of Java?
A: Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded
Q: 4 Why is Java Architectural Neutral?
A: Its compiler generates an architecture-neutral object file format, which makes the compiled code to be
executable on many processors, with the presence of Java runtime system.
Q: 5 How Java enabled High Performance?
A: Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns
Java bytecode, which is a program that contains instructions that must be interpreted into instructions that can
be sent directly to the processor.
Q:6 Why Java is considered dynamic?
A: It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
Q:7 What is Java Virtual Machine and how it is considered in context of Javas platform independent
feature?
A: When Java is compiled, it is not compiled into platform specific machine, rather into platform independent
byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever
platform it is being run.
Q:8 List two Java IDEs?
A: Netbeans, Eclipse, etc.
Q:9 List some Java keywords(unlike C, C++ keywords)?
A: Some Java keywords are import, super, finally, etc.
Q:10 What do you mean by Object?

A: Object is a runtime entity and its state is stored in fields and behavior is shown via methods. Methods
operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
Q:11 Define class?
A: A class is a blue print from which individual objects are created. A class can contain fields and methods to
describe the behavior of an object.
Q:12 What kind of variables a class can consist of?
A: A class consist of Local variable, instance variables and class variables.
Q: 13 What is a Local Variable
A: Variables defined inside methods, constructors or blocks are called local variables. The variable will be
declared and initialized within the method and it will be destroyed when the method has completed.
Q:14 What is a Instance Variable
A: Instance variables are variables within a class but outside any method. These variables are instantiated
when the class is loaded.
Q: 15 What is a Class Variable
A: These are variables declared with in a class, outside any method, with the static keyword.
Q:16 What is Singleton class?
A: Singleton class control object creation, limiting the number to one but allowing the flexibility to create
more objects if the situation changes.
Q:17 What do you mean by Constructor?
A: Constructor gets invoked when a new object is created. Every class has a constructor. If we do not
explicitly write a constructor for a class the java compiler builds a default constructor for that class.
Q: 18List the three steps for creating an Object for a class?
A: An Object is first declared, then instantiated and then it is initialized.
Q: 19What is the default value of byte datatype in Java?
A: Default value of byte datatype is 0.
Q: 20 What is the default value of float and double datatype in Java?

A: Default value of float and double datatype in different as compared to C/C++. For float its 0.0f and for
double its 0.0d.
Q: 21 How finally used under Exception Handling?
A: The finally keyword is used to create a block of code that follows a try block. A finally block of code
always executes, whether or not an exception has occurred.
Q:22 What things should be kept in mind while creating your own exceptions in Java?
A: While creating your own exception:

All exceptions must be a child of Throwable.


If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.

You want to write a runtime exception, you need to extend the RuntimeException class.

Q:23 Define Inheritance?


A: It is the process where one object acquires the properties of another. With the use of inheritance the
information is made manageable in a hierarchical order.
Q:24 When super keyword is used?
A: If the method overrides one of its superclass's methods, overridden method can be invoked through the use
of the keyword super. It can be also used to refer to a hidden field
Q:25 What is Polymorphism?
A: Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism
in OOP occurs when a parent class reference is used to refer to a child class object.
Q:26 What is Abstraction?
A: It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves
the maintainability of the system.
Q:27 What is Abstract class
A: These classes cannot be instantiated and are either partially implemented or not at all implemented. This
class contains one or more abstract methods which are simply method declarations without a body.
Q: 28 When Abstract methods are used?
A: If you want a class to contain a particular method but you want the actual implementation of that method
to be determined by child classes, you can declare the method in the parent class as abstract.

Q:29 What is Encapsulation?


A: It is the technique of making the fields in a class private and providing access to the fields via public
methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the
fields within the class. Therefore encapsulation is also referred to as data hiding.
Q:30 What is the primary benefit of Encapsulation?
A: The main benefit of encapsulation is the ability to modify our implemented code without breaking the code
of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our
code.
Q: 31What is an Interface?
A: An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the
abstract methods of the interface.
Q:32 Define Packages in Java?
A: A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations )
providing access protection and name space management.
Q:33 Why Packages are used?
A: Packages are used in Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations, etc., easier.
Q:34 What do you mean by Multithreaded program?
A: A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
Q:35 What is an applet?
A: An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
Q:36 An applet extend which class?
A: An applet extends java.applet.Applet class
Q:37 Define JRE i.e. Java Runtime Environment?
A: Java Runtime Environment is an implementation of the Java Virtual Machine which executes Java
programs. It provides the minimum requirements for executing a Java application;
Q:38 What is JAR file?

A: JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR
files are built on ZIP file format and have .jar file extension.
Q:39 What is a WAR file?
A: This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to
distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.
Q:40 Define JIT compiler?
A: It improves the runtime performance of computer programs based on bytecode.

Das könnte Ihnen auch gefallen