0% found this document useful (0 votes)
13 views54 pages

Java Course Contents

The document provides an overview of Java programming, highlighting its object-oriented nature, platform independence, and security features. It covers fundamental concepts such as data types, control statements, inheritance, multi-threading, and exception handling, along with examples of code implementation. Additionally, it discusses the distinction between structured programming and object-oriented programming, emphasizing the benefits of encapsulation and software reuse in Java.

Uploaded by

warriorc063
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views54 pages

Java Course Contents

The document provides an overview of Java programming, highlighting its object-oriented nature, platform independence, and security features. It covers fundamental concepts such as data types, control statements, inheritance, multi-threading, and exception handling, along with examples of code implementation. Additionally, it discusses the distinction between structured programming and object-oriented programming, emphasizing the benefits of encapsulation and software reuse in Java.

Uploaded by

warriorc063
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

1.

INTRODUCTION

Java is a pure object oriented programming language and some of the key advantages of
Java Programming are :

 Object Oriented − In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
 Platform Independent − Unlike many other programming languages including C
and C++, 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 the Virtual Machine (JVM) on whichever platform it is being run
on.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in ANSI
C with a clean portability boundary, which is a POSIX subset.

DIFFERENT RELEASE AND TIME LINE

Example:
public class MyFirstJavaProgram

public static void main(String []args)

System.out.println("Hello World"); // prints Hello World

} //eoc

NB: A different number of programs can be taken into account for programming practice(s)
with respect different concepts.

Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

2
Control Statements :

There may be a situation when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

Variable(s): A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable.

Array: Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.

3
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Example: int Roll[] = new int [5] OR

int[] Roll = new int[5] OR int Roll[]={1,2,3,4,5}

Interface: An interface is a reference type in Java. It is similar to class. It is a collection of


abstract methods. A class implements an interface, thereby inheriting the abstract methods of
the interface.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.

Example:
interface Animal{
public void eat();
public void dance();
}

Class MyAnimal implements Animal {


Public void eat(){
System.out.println(“Cow eats only grass” ) ;
Public void dance(){
System.out.print(“ Cow does not dance”);
}// eoc

IDENTIFIERS, KEYWORDS AND VARIABLES


In java program, every word is classified as either an identifiers or a keyword.

1. IDENTIFIER- Identifiers are the names that we specify for the variables, types,
classes, objects, methods and labels in the java program. Declaring these in a
declaration section creates identifiers. An identifier is a programmer-defined

4
name that represent some elements of a program. Variable names and class
names are the examples of the identifiers.

*Rules for naming identifiers-

The following rules are used when naming identifiers:

1. An identifier is a combination of one or more letters a-z. A-Z, digits,


underscore(_) or dollar sign character in which the first letter must be a letter
or an underscore or a dollar($) sign.

2. An identifier can of any length.

3. Uppercase and lowercase characters are distinct.

4. They cannot include spaces.

5. For example, area, radius, first_name are some identifiers.

2. Keyword: are those special words whose meanings are prefixed by the java
compiler. Please note that you can’t use keyword to name classes or variables.
Also note that the keyword also called as the reserved words. some examples of
java’s keywords are as follow-

abstract char double for int private super try Boolean class else
goto interface protected switch void break const extends if long
public synchronized volatile byte continue final implements native
return this while case default finally import new short throw catch
do float instanceof package static transient

3. Variable- A variable is a container that holds values that are used in a Java
program. Every variable must be declared to use a data type. For example, a
variable could be declared to use one of the eight primitive data types: byte,
short, int, long, float, double, char or boolean.

*Declaration of variable

To declare a variable in Java, all that is needed is the data type followed by
the variable name:

int numberOfDays;

5
In the above example, a variable called "numberOfDays" has been declared
with a data type of int. Notice how the line ends with a semi-colon (;).

DATA TYPES (IN JAVA)


The platform independent feature of Java is achieved through bytecode. The
eight primitive data types are: byte, short, int, long, float, double, boolean,
and char. The java.lang.String class represents character strings.

DATA TYPES AND THEIR SIZES


Data types Size Range

Integers

Byte 8-bits -128 to +127

short 16-bits -32768 to +32767

int 32-bits -2³¹ to 2³¹ - 1

long 64-bits -2⁶³ to 2⁶³ - 1

Floating-point numbers

float 32-bits (IEEE 754) -3.4е38 to 3.4 е38

double 64-bits (IEEE 754) -1.7е308 to 1.7е308

6
Characters

char 16-bits 0 to 65,536

Boolean

boolean 1-bit True/false

object n/a n/a

OPERATORS ( IN JAVA)

1. ARITHMETIC OPERATORS

2. RELATIONAL OPERATORS

7
3. LOGICAL OPERATORS

8
2. Exception & Graphics Programming

Inheritance
Inheritance: Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the information is
made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent
class).
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

Example:

Class Aone { int a=5; int b=55;

Class ChkAone extends Aone { // This is single inheritance

// interface can be implemented in this class

Public static void main() { System.out.print(a);


System.out.print(b); } // eoc

Example:

//inheritence using super and this


class Person
{
String name;
String address;
int age;
void printInfo()
{
System.out.println(this.name);
System.out.println(this.address);
System.out.println(this.age);
}
Person(String name,String address,int age)
{
this.name=name;
this.address=address;
this.age=age;
}
}
class Student extends Person
{
9
String roll_no;
Student(String name,String address,int age,String roll_no)
{
super(name,address,age);
this.roll_no=roll_no;
}
void printInfo()
{
super.printInfo();
System.out.println(this.roll_no);
}
}
class A11
{
public static void main(String[] ar)
{
Student s=new Student("Ankit
Sharma","MEERUT",26,"0712810015");
s.printInfo();
}
}

NB: Different FORMS of Inheritance can be implemented by using interface technology for
multiple inheritance.

Distinguish between structured programming and OOP


Structured programming Object-Oriented Programming
1. Top-down approach is followed. 1. Bottom-up approach is followed.
2. The main focus is on algorithm and 2. The main focus is on object and
control flow. classes.
3. A program is divided into a number of
sub-modules or functions or procedures. 3. A program is organized by having a
4. Functions are independent of each number of classes and objects.
other. 4. Each class is related in hierarchical
5. It views data and functions are two manner.
separate entities. 5. It views data and functions as a single
6. Software reuse is not possible. entity.
7. Functions call is used. 6. Software reuse is possible.
8. Function abstraction is used. 7. Message passing is used.
9. Data-driven technique is used. 8. Data abstraction is used.
9. It is driven by delegation of
10. Algorithm is given importance. responsibilities.
11. No encapsulation-data and functions 10. Data is given more importance.
separate. 11. Encapsulation is done here and it
treats code and data is a single unit
12. Costlier maintenance. called as a class.
10
12. Cheaper maintenance.

Multi-Threading: Java is a multi-threaded programming language which means we


can develop multi-threaded program using Java. A multi-threaded program contains
two or more parts that can run concurrently and each part can handle a different task
at the same time making optimal use of the available resources specially when your
computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing
resources such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single application
into individual threads. Each of the threads can run in parallel. The OS divides
processing time not only among different applications, but also among each thread
within an application.
Multi-threading enables you to write in a way where multiple activities can proceed
concurrently in the same program.

Life Cycle of a Thread: A thread goes through various stages in its life cycle. For example,
a thread is born, started, runs, and then dies. The following diagram shows the complete life
cycle of a thread.

11
Following are the stages of the life cycle −
 New − A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread waits
for another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

Example:

class ThreadDemo extends Thread {

public void run() {

try { for(int i = 4; i > 0; i--) { System.out.println(i);

Thread.sleep(50); // Let the thread sleep.

}catch (Exception e) { System.out.println(e); } }


//eorun()

public class TestThread { public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo(); T1.start();

12
ThreadDemo T2 = new ThreadDemo(); T2.start();

} // eom

}// eoc

Example
//String class
class A22
{
public static void main(String[] ar)
{
String s1=new String("A QUICK FOX JUMP OVER THE LAZY
DOG");
System.out.println(s1.length());
System.out.println(s1.charAt(5));
System.out.println(s1.indexOf('A'));
System.out.println(s1.indexOf('A',5));
System.out.println(s1.substring(4));
System.out.println(s1.substring(4,20));
System.out.println(s1.equals("A QUICK fox JUMP OVER THE
LAZY DOG"));
System.out.println(s1.equalsIgnoreCase("A QUICK fox JUMP
OVER THE LAZY DOG"));

}
}

//Constructor
class Employee
{
int a=20;
Employee()
{
System.out.println("SIMPLE CLASS");
a=220;
System.out.println(a);
}
{
System.out.println(a);
}
}
class A52
{
public static void main(String[] ar)
{
Employee e=new Employee();
} }

//Parsing

13
class M1
{
public static void main(String[] ar)
{
int p=Integer.parseInt(ar[0]);
for(int i=p;i>0;i--)
{
for(int j=0;j<i;j++)
{
System.out.print('*');
}
System.out.print("\n");
}
}
}

Handling/ Event

Exception: 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.
Example: as above in try-catch block. Different number of Exceptions must be tried in

programming form.

//Exception Handling
class Customer
{
int balance;
Customer(int balance)throws Exception
{
if(balance>500)
{
this.balance=balance;
}
else
{
throw new Exception("BALANCE CANT BE LESS THAN 500");

14
}
}
}
class A24
{
public static void main(String[] ar)
{
try
{
Customer c=new Customer(200);
}catch(Exception ee)
{
System.out.println("this is the error"+ee);
}
}
}

Wrapper classes are those whose objects wraps a primitive data type within them.
In the java.lang package java provides a separate class for each of the primitive data types
namely Byte, Character, Double, Integer, Float, Long, Short.
At the time of instantiation, these classes accept a primitive datatype directly, or in the form
of String.
Wrapper classes provide methods to, convert primitive datatypes within them to String
objects and, to compare them with other objects etc.
Using wrapper classes, you can also add primitive datatypes to various Collection objects
such as ArrayList, HashMap etc. You can also pass primitive values over a network using
wrapper classes.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify
the arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in
this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.

Distinguish between interface and implementation


Interface Implementation
1. It is a user’s view point (What 1. It is the supplier’s view point (How
part). part).
2. It is used to interact outside 2. It describes how the delegated
world. responsibility is carried out.
3. User is permitted to access the 3. Functions or methods are
interfaces only. permitted to access the data. So,
15
4. It encapsulates the knowledge supplier is capable of accessing
about the object. data and interfaces.

JUST IN TIME COMPILER ( J I T)

Each web browser that supports JAVA VIRTUAL MACHINE (JVM) built right into
it and it loads .class file. It is also evident that when a program is interpreted, it
generally runs substantially slower then it would run if compiled to an
executable code. But remember that the use of the byte-code enables the java run
time system to execute program faster. Sun has introduced just in time compiler
(JIT) for byte- code. Just in time compiler (JIT compiler) is part of JVM. Its job is to
take the generic i.e. cross-platform byte-codes and compile them into more
machine specific instructions allowing the program to run faster. Even though it
is referred to as a JIT compiler, it is the part of the virtual machine. When JIT is
part of a JVM, it compiles byte-codes into executable code in real time, on
demand basis, this is so because JVM perform various run time checks that can be
done only at the run-time. Instead, JIT compiles the code as it is needed during
the execution. JVM code is designed so that it is easy to translate it into machine
instructions for real machine, so the second part of the translation to real
machine instructions is done in the browser on the user’s machine. Please
understand that the browser takes the applet JVM code that it gets from the
server and translates from JVM code to the machine code the browser is
using. This compiler in the browser is often called as a JIT compiler. Also
understand that JIT means that the last part of the compilation is done
before running the program.

16
Autoboxing: Automatic conversion of primitive types to the object of their corresponding
wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.

Example:

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object


of a wrapper class to its corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double, etc.

17
Concept of WRAPPER CLASS

18
CONCEPT OF VECTOR CLASS

Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.

Example:

import java.util.*;

public class VectorDemo { public static void main(String args[]) {

// initial size is 3, increment is 2

Vector v = new Vector(3, 2); System.out.println("Initial size: " + v.size());

System.out.println("Initial capacity: " + v.capacity()); v.addElement(new


Integer(1));

v.addElement(new Integer(2)); v.addElement(new Integer(3));


19
v.addElement(new Integer(4)); System.out.println("Capacity after four additions: " +
v.capacity());

v.addElement(new Double(5.45));

System.out.println("Current capacity: " + v.capacity());

v.addElement(new Double(6.08)); v.addElement(new Integer(7));

System.out.println("Current capacity: " + v.capacity());

v.addElement(new Float(9.4)); v.addElement(new Integer(10));

System.out.println("Current capacity: " + v.capacity());

v.addElement(new Integer(11)); v.addElement(new Integer(12));

System.out.println("First element: " + (Integer)v.firstElement());

System.out.println("Last element: " + (Integer)v.lastElement());

if(v.contains(new Integer(3)))

System.out.println("Vector contains 3.");

// enumerate the elements in the vector.

Enumeration vEnum = v.elements(); System.out.println("\nElements in vector:");

while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " ");

System.out.println();

3. GRAPHICS PROGRAMMING IN JAVA/ APPLETs/ AWT

Graphics Class

 In Java, the drawing takes place via a Graphics object, this is an instance of
the java.awt.Graphics class.
 Each Graphics object has its own coordinate system and all the methods of Graphics
including those for drawing Strings, lines, rectangles, circles, polygons and etc.
20
 We can get access to the Graphics object through the paint(Graphics g) method.
 We can use the drawRoundRect() method that accepts x-coordinate, y-
coordinate, width, height, arcWidth, and arc height to draw a rounded rectangle.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RoundedRectangleTest extends JFrame {
public RoundedRectangleTest() {
setTitle("RoundedRectangle Test");
setSize(350, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawRoundRect(10, 50, 150, 150, 50, 30); // to draw a rounded rectangle.
}
public static void main(String []args) {
new RoundedRectangleTest();
}
}

NB: The concept of event handling/ AWT may either be practiced with Applet programing as
per the library functions ( Methods ) availabe in Java.

//awt
import java.lang.*;
import java.awt.*;
class A45
{
public static void main(String[] ar)
{
Frame f=new Frame();
f.setSize(500,500);
f.setVisible(true);
}
}

21
//graphics example
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Frame1 extends Frame
{
Label l=new Label();
Button b=new Button();
Frame1(String title)
{
this.setSize(500,600);
this.setLayout(null);
this.add(l);
l.setBounds(10,100,200,30);
this.add(b);
b.setBounds(210,100,200,30);
b.addActionListener(new ActionListener(){public void
actionPerformed(ActionEvent e){add();}});
this.addMouseMotionListener(new MouseAdapter(){public
void mouseMoved(MouseEvent e){f1(e);}});
this.addMouseMotionListener(new MouseAdapter(){public
void mouseMoved(MouseEvent e){add();}});
}
int r=0;
void add()
{
r=r+60;
repaint();
}
void f1(MouseEvent e)
{
int x=e.getX();
int y=e.getY();
l.setText("x="+x+"y="+y);
}
public void paint(Graphics g)
{
g.drawRect(10,35,100,50);
g.setColor(Color.RED);
g.fillRect(110,35,100,50);
g.fillOval(250,250,200,20);
g.fillArc(30,400,200,100,0+r,30);
g.setColor(Color.GREEN);
g.fillArc(30,400,200,100,30+r,60);
g.setColor(Color.YELLOW);
g.fillArc(30,400,200,100,90+r,60);
g.setColor(Color.GRAY);
g.fillArc(30,400,200,100,150+r,90);
g.setColor(Color.PINK);
g.fillArc(30,400,200,100,240+r,120);

}
22
}
class A73
{
public static void main(String[] ar)
{
new Frame1("").setVisible(true);
}
}

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.
There are some important differences between an applet and a standalone Java application,
including the following −
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.

Life Cycle of an Applet

Four methods in the Applet class gives you the framework on which you build any serious
applet −
 init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having
gone off to other pages.
 stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.
import java.applet.*;
import java.awt.*;
23
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}

The Applet Class

Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
These include methods that do the following −
 Get applet parameters
 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet

Invoking an Applet

An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an
example that invokes the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>

Note − You can refer to HTML Applet Tag to understand more about calling applet from
HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width
and height are also required to specify the initial size of the panel in which an applet runs.
The applet directive must be closed with an </applet> tag.

24
If an applet takes parameters, values may be passed for the parameters by adding <param>
tags between <applet> and </applet>. The browser ignores text and other tags between the
applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.

Event Handling

Applets inherit a group of event-handling methods from the Container class. The Container
class defines several methods, such as processKeyEvent and processMouseEvent, for
handling particular types of events, and then one catch-all method called processEvent.
In order to react to an event, an applet must override the appropriate event-specific method.

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;

public class ExampleEventHandling extends Applet implements MouseListener {


StringBuffer strBuffer;

public void init() {


addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}

public void start() {


addItem("starting the applet ");
}

public void stop() {


addItem("stopping the applet ");
}

public void destroy() {


addItem("unloading the applet");
}

void addItem(String word) {


System.out.println(word);
strBuffer.append(word);
repaint();
}
public void paint(Graphics g) {

25
// Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);

// display the string inside the rectangle.


g.drawString(strBuffer.toString(), 10, 20);
}

public void mouseEntered(MouseEvent event) {


}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}

Now, let us call this applet as follows –

<html>
<title>Event Handling</title>
<hr>
<applet code = "ExampleEventHandling.class"
width = "300" height = "300">
</applet>
<hr>
</html>
Initially, the applet will display "initializing the applet. Starting the applet." Then once you
click inside the rectangle, "mouse clicked" will be displayed as well.

4. Streams & File Handling

Stream represents a sequence of objects from a source, which supports aggregate operations.
Following are the characteristics of a Stream −

26
 Sequence of elements − A stream provides a set of elements of specific type in a
sequential manner. A stream gets/computes elements on demand. It never stores the
elements.
 Source − Stream takes Collections, Arrays, or I/O resources as input source.
 Aggregate operations − Stream supports aggregate operations like filter, map, limit,
reduce, find, match, and so on.
 Pipelining − Most of the stream operations return stream itself so that their result can
be pipelined. These operations are called intermediate operations and their function is
to take input, process them, and return output to the target. collect() method is a
terminal operation which is normally present at the end of the pipelining operation to
mark the end of the stream.
 Automatic iterations − Stream operations do the iterations internally over the source
elements provided, in contrast to Collections where explicit iteration is required.

The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, object, localized
characters, etc.
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly
used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −

import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

27
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
} } } }

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file −
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

28
Reading and Writing Files

As described earlier, a stream can be defined as a sequence of data. The InputStream is used
to read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file,
if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write
the file −
OutputStream f = new FileOutputStream("C:/java/hello")

29
Following constructor takes a file object to create an output stream object to write the file.
First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can
be used to write to stream or to do other operations on the stream.
NB: Depending upon the operations the corresponding methods/ objects may be called upon
accordingly.

//DataInputStream
import java.io.*;
class A30
{
public static void main(String[] ar)throws IOException
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println(ds.readInt());
System.out.println((ds.write());
}
}

UNIT-II

5. SWING

SWING - Overview
Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA
based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement
of AWT API, since it has almost every control corresponding to AWT controls. Swing
component follows a Model-View-Controller architecture to fulfill the following criterias.
 A single API is to be sufficient to support multiple look and feel.
 API is to be model driven so that the highest level API is not required to have data.
 API is to use the Java Bean model so that Builder Tools and IDE can provide better
services to the developers for use.
30
MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.
 Model represents component's data.
 View represents visual representation of the component's data.
 Controller takes the input from the user on the view and reflects the changes in
Component's data.
 Swing component has Model as a seperate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.

Swing Features

 Light Weight − Swing components are independent of native Operating System's API
as Swing API controls are rendered mostly using pure JAVA code instead of
underlying operating system calls.
 Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
 Highly Customizable − Swing controls can be customized in a very easy way as visual
apperance is independent of internal representation.
 Pluggable look-and-feel − SWING based GUI Application look and feel can be
changed at run-time, based on available values.

SWING - Environment Setup


This section guides you on how to download and set up Java on your machine. Please use the
following steps to set up the environment.
Java SE is freely available from the link Download Java. Hence, you can download a version
based on your operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine.
Once you have installed Java on your machine, you would need to set the environment
variables to point to the correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:\Program Files\java\jdk directory −


Step 1 − Right-click on 'My Computer' and select 'Properties'.
Step 2 − Click the 'Environment variables' button under the 'Advanced' tab.
Step 3 − Alter the 'Path' variable so that it also contains the path to the Java executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path
to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −


Step 1 − Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET
PATH=%PATH%;C:\Program Files\java\jdk\bin'.
31
Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingControlDemo {


private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;

public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));

headerLabel = new JLabel("",JLabel.CENTER );


statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");

JButton okButton = new JButton("OK");


JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");

okButton.setActionCommand("OK");
32
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());

controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if( command.equals( "OK" )) {


statusLabel.setText("Ok Button clicked.");
} else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
} else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}

Verify the following output.

33
6. Java - Networking

The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols −
 TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
 UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.

This chapter gives a good understanding on the following two subjects −


 Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.
 URL Processing − This would be covered separately. Click here to learn about URL
Processing in Java language.

Socket Programming

Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket
to a server.
When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and reading
from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets −
 The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
 The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
 After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
 The constructor of the Socket class attempts to connect the client to the specified
server and the port number. If communication is established, the client now has a
Socket object capable of communicating with the server.
 On the server side, the accept() method returns a reference to a new socket on the
server that is connected to the client's socket.

34
After the connections are established, communication can occur using I/O streams. Each
socket has both an OutputStream and an InputStream. The client's OutputStream is connected
to the server's InputStream, and the client's InputStream is connected to the server's
OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the
same time. Following are the useful classes providing complete set of methods to implement
sockets.

Socket Client Example

The following GreetingClient is a client program that connects to a server by using a socket
and sends a greeting, and then waits for a response.
// File Name GreetingClient.java
import java.net.*;
import java.io.*;

public class GreetingClient {

public static void main(String [] args) {


String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);

System.out.println("Just connected to " + client.getRemoteSocketAddress());


OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);

out.writeUTF("Hello from " + client.getLocalSocketAddress());


InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);

System.out.println("Server says " + in.readUTF());


client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Socket Server Example

The following GreetingServer program is an example of a server application that uses the
Socket class to listen for clients on a port number specified by a command-line argument −
// File Name GreetingServer.java
import java.net.*;
import java.io.*;

35
public class GreetingServer extends Thread {
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {


serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();

System.out.println("Just connected to " + server.getRemoteSocketAddress());


DataInputStream in = new DataInputStream(server.getInputStream());

System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();

} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break; } } }

public static void main(String [] args) {


int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}

36
7. Advanced Applet Programming

Hierarchy of Applet

As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Applet class.

Example of EventHandling in JApplet:

import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){

tf=new JTextField();
tf.setBounds(30,40,150,20);

b=new JButton("Click");
b.setBounds(80,150,70,40);

37
add(b);add(tf);
b.addActionListener(this);

setLayout(null);
}

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}
}

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.

Example of Painting in Applet:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{

public void init(){


addMouseMotionListener(this);
setBackground(Color.red);
}

public void mouseDragged(MouseEvent me){


Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
38
}
public void mouseMoved(MouseEvent me){}

In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. T
method of Component class returns the object of Graphics.

myapplet.html

1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Parameter in Applet

We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:

Example of using parameter in Applet:

import java.applet.Applet;
import java.awt.Graphics;

public class UseParam extends Applet{

public void paint(Graphics g){


String str=getParameter("msg");
g.drawString(str,50, 50);
}

myapplet.html
39
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>

40
8. Java JDBC & Packages

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:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

41
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There are 4
drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge drive
method calls into the ODBC function calls. This is now discouraged because of thin driver.

42
Java Database Connectivity with 5 Steps
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection

Example

import java.sql.*;
// implementing DriverAction interface
class JdbcExample implements DriverAction{
// implementing deregister method of DriverAction interface
@Override
public void deregister() {
System.out.println("Driver deregistered");
}
public static void main(String args[]){
try{
// Creating driver instance
Driver driver = new com.mysql.jdbc.Driver();
// Creating Action Driver
DriverAction da = new JdbcExample();
// Registering driver by passing driver and driverAction
DriverManager.registerDriver(driver, da);
// Creating connection
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student"
,"root","mysql");
//Here student is database name, root is username and password is mysql
Statement stmt=con.createStatement();
// Executing SQL query
ResultSet rs=stmt.executeQuery("select * from user");
while(rs.next()){
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));

43
}
// Closing connection
con.close();
// Calling deregisterDriver method
DriverManager.deregisterDriver(driver);
}catch(Exception e){ System.out.println(e);}
}

//Example

import java.sql.*;

class A105
{
public static void main(String[] ar)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE
","System","java");
Statement s=con.createStatement();
String query="insert into sliet
values('Ankit','GAAYA',20)";
s.executeUpdate(query);
}catch(Exception ee)
{
System.out.println(ee+""); } } }

NB: A number of operations can be performed according to the need of the concepts.
Similarly, the client server model can be practicized with servlet technology.

JSP

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.

44
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.

The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming

45
language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web
page.

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low. The advantages of Servlet are as follows:

1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection , etc.
4. Secure: because it uses java language.

46
Objective Type Question-Bank (MCQ)

for Java Programming ( CS-321)

All objective type(s) questions [ 01-50 ], Short Answer type [ 5 questions 1-80], Long
Answer/ descriptive type questions [81-100]

Q1. Number of primitive data types in Java are? ( Ans. 08)

Q2. What is the size of float and double in java? ( Ans. 32 and 64 )

Q3. Automatic type conversion is possible in which of the possible cases? ( Ans. int to long
)

Q4. When an array is passed to a method, what does the method receive? ( Ans. Reference
of the array )

Q5. Arrays in java are: (Ans. objects)

Q6. compareTo() returns : (Ans. int value)

Q7. To which package does the class string belong to : ( Ans. java.lang. )

Q8. Identify the output of the following program. ( Ans. onetwo)

Public class Test{


Public static void main(String argos[]){
String str1 = “one”; String str2 = “two”;
System.out.println(str1.concat(str2)); } }

Q9. Find the output of the following code. ( Ans. Compilation Error)

int ++a = 100;


System.out.println(++a; )

Q10. Identify the return type of a method that does not return any value. (Ans. void)

Q11. Identify the modifier which cannot be used for constructor. (Ans. static)

Q12. What is the variables declared in a class for the use of all methods of the class called?
(Ans. instance variable)

Q13. What is the implicit return type of constructor?


(Ans. Implicit return type of constructor is the class object in which it is defined. )

Q14. Identify the prototype of the default constructor. Public class Solution {}
(Ans. public Solution() )

Q15. What is Runnable? (Ans. interface)


47
Q16. Which of the following exception is thrown when divided by zero statement is
executed?
NullPointerException
NumberFormatException (Ans.)
ArithmeticException
None

Q17 Where is System class defined? (Ans. java.lang.package)

Q18. Which of the following statements are true about finalize() method?

It can be called Zero or one times (Ans.)


It can be called Zero or more times
It can be called Exactly once
It can be called One or more times

Q19. Identify the incorrect Java feature.


Object oriented
Use of pointers (Ans.)
Dynamic
Architectural neural

Q20. Which of the following is used to find and fix bugs in the program?
JDK JRE JVM JDB (Ans.)

Q21. Who invented Java Programming? (Ans. James Gosling )

Q22. Which of these cannot be used for a variable name in Java? (Ans. keywords)

Q23. What is the extension of java code files? (Ans. java)

Q24. Which environment variable is used to set the java path?

a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME (Ans.)

Q25. What is the use of “this” keyword in Java? (Ans. to address the current class
references)

Q26. Which of the following is not an OOPS concept in Java?


a) Polymorphism
b) Inheritance
c) Compilation (Ans.)
d) Encapsulation

Q27. What is the extension of compiled java classes? (Ans. *.class extension)

48
Q28. Which of these statements is incorrect about Thread?
a) start() method is used to begin execution of the thread
b) run() method is used to begin execution of a thread before start() method in special cases
(Ans.)
c) A thread can be formed by implementing Runnable interface only
d) A thread can be formed by a class that extends Thread class

Q29. Which of the following can be operands of arithmetic operators?

a) Numeric
b) Boolean
c) Characters
d) Both Numeric & Characters (Ans.)

Q30. Modulus operator, %, can be applied to which of these?


a) Integers b) Floating – point numbers
c) Both Integers and floating – point numbers (Ans.) d) None of the mentioned

Q31. In java, jar stands for_____.

a. java Archive Runner


b. Java Application Resource
c. Java Application Runner
d. None of the above (Ans.)

Q32. If a thread goes to sleep

a. It releases all the locks it has.


b. It does not release any locks. (Ans.)
c. It releases half of its locks.
d. It releases all of its lock except one.

Q33. Which statement about a valid .java file is true?


A. It can only contain one class declaration.
B. It can contain one pulic class declaration and one public interface definition.
C. It must define at least one public class.
D. It may define at most one public class. (Ans.)

Q34. An interface with no fields or methods is known as a ______.

a. Runnable Interface b. Marker Interface (Ans) c. Abstract Interface d.


CharSequence Interface

Q35. Which keyword is used for accessing the features of a package?


a. package b. import (Ans) c. extends d. export

49
Q36. What is meant by the classes and objects that dependents on each other?
a. Tight Coupling (Ans) b.Cohesion c. Loose Coupling d. None of the above

Q37. How many threads can be executed at a time?

a. Only one thread b. Multiple threads (Ans) c).Only main (main() method) thread
d. Two threads

Q38. If a thread goes to sleep


a. It releases all the locks it has.
b. It does not release any locks. (Ans)
c It releases half of its locks.
d It releases all of its lock except one.

Q39. Which component is used to compile, debug and execute the java programs?
a) JRE b) JIT c) JDK (Ans) d) JVM

Q40. String class belongs to __________ package


a. java.awt b. java.lang ( Ans) c. java.applet d. java.string

Q41. Which type of loop is best known for its boolean condition that controls entry to the
loop?
A. do-while loop B. for (traditional) C. for-each D. While (Ans)
Q42. Java is an object-oriented programming language developed by ____
a. Oracle b. Sun Micro Systems (Ans) c.Unix d. Netcape

Q43. Java is also a general-purpose programming language for developing programs that are
easly usable and portable across different ________
a. Tables b. Stands c. Libraries d. Platforms (Ans)

Q44. Using ________ one can take full advantage of object-oriented methodology and its
capabilities of creating flexible, modular and reusable code.
a. Java Language (Ans) b. C- Language c. Basic- Language d. PHP

Q45. The so-called “Virutal” computer is known as _____


a. JMV b. VMJ. C. JVM (Ans) d. MVJ

Q46. The machine language for the Java Virtual Machine is called ___
a. Compiler b. Interpreter (Ans) c. Translator d. None of these

Q47. A Java program should have at least one ___ and it must have main __ in it.
a. Class, Procedure b. Class, Variable c. Class, method (Ans) d. Class, code

Q48. Java source file can be creaated using any plain _____ text editor.
a. Native b. Original c. ASCII (Ans d. Binary

Q49. Java ___ files are given the same name as the class defined with an extension of Java.
a. Beginning b. Destination c. Source (Ans) d. Binary

50
Q50. In Java the ___ name is case sensitive.
a. File b. Folder c. Class (Ans ) d. First

Short Answers type Questions

Q51. What is JAVA?

Q52. What are the features of JAVA?

Q53. How does Java enable high performance?

Q 54. What do you mean by Constructor?

Q55. What is meant by the Local variable and the Instance variable?

Q56. What is a Class?

Q57. What is Inheritance?

Q58. What is Polymorphism?

Q59. What is String in Java?

Q60. What is Encapsulation in Java?

Q61. What is Method Overloading ?

Q62. What is Method Overriding?

Q63. What is Abstract Class?

Q64. What is Access Specifier?

Q65. What is Interface?

Q66. What is Inheritance in Java?

Q67. What is Wrapper class?

Q68. What is Vector class?

51
Q69. What is Array and ArrayList?

Q70. What is Exception?

Q71. What are different ways to handle the Exception?

Q72. What is ‘final’ key workd?

Q73. What is Thread ?

Q74. What is Class & Object?

Q75. What is Applet?

Q76. What is a Package in Java?

Q77. What is conditional operator?

Q78. What is JVM?

Q79. What is Event?

Q80. What is Gargbage Collection in Java?

Descriptive Questions/ Long-Answer type questions

Q81. Discuss various features of Java?

Q82. Discuss different data types in Java with a suitable programming code.

Q83. Discuss the different control structures in Java with a suitable progmming code.

Q84. Write a program to read a number form the keyboard and find its factorial.

Q85. Explain that how ‘Exception handling is a tool in Java’ .

Q86. Explain the concept of Arrays in Java and demonstrate the additoin of matix having a
size 3x3.

Q87. Explain different types of Inheritance in Java.

Q89. What is multithreaded programming? Show how threads can be created in Java?

Q90 Explain the following AWT components – Label, Checkbox, Radio Button and List
control with a suitable programming code in Java.

Q91. Discuss the components of JDBC in detail.


52
Q92. Explain the Encapsulation principle and method Overriding concept in Java.

Q93. Explain the life cycle of an Applet in detail.

Q94. Explain the life cycle of a Thread in detail.

Q95. Explain the concept and significance of Autoboxing and Wrapper class in Java.

Q96. Explain the concept of Iostreams in Java.

Q96. Explain the concept of event-driven programming in java with suitable example.

Q97. Explain the concept of User-defined Package. Also demonstrate with a suitable
program.

Q98. Explain various methods associated withWRAPPER class in detail.

Q99. Explain the cocept of passing parameter to Applets in detail.

Q100. Explain the significant features of Vector class and methods associated with it. How
Vector is best than the concept of Arrays

53
LIST OF PRACTICALS

1) Write a Program to create the variables of different data types and also show the effect
of type conversions. Also demonstrate the output of each.
2) Write a program to illustrate the behaviour of print() and println() methods of System
class.
3) Write a program to convert the given temperature in Fahrenheit to Celsius.
4) Write a program to find all the numbers of and sum of all the integers
5) Write a program to print multiplication table using do-while loop.
6) Write a program to reverse the digits of a number using while loop.
7) Write a program to print the Fibonacci series.
8) Write a prorgram to read a number from console and calculate its factorial.
9) Write a program to illustrate the concept of constructors.
10) Write a program to illustrate the concept of single (multiple using interface)
inheritance.
11) Write a program to illustrate the use of an array for sorting a list of numbers.
12) Write a program to illustrate the use of some commonly used wrapper class methods.
13) Write a program to illustrate the use of Thread class for creating and running threads
in an application.

54

You might also like