Advanced Java Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

SCHOOL OF COMPUTING AND INFORMATION

TECHNOLOGY

Advanced Java Programming Lab Manual

III Year V Semester

B. Tech in CSIT
2023-2024

1
AJP Lab Manual REVA University

List of Experiments

Sl.N List of Programs Page


o. Number

1 Vision and Mission of the University 6

2 Vision and Mission of the School 6

3 Program Educational Objective 7

4 Program Specific Outcome 7

5 Program Outcome 8

6 Course Details 9
• Course Objectives
• Lab Requirement
• Guidelines to Students
• Course Outcomes 10
7
• Conduction of Practical Examination
• CO-PO-PSO Mapping
Lab Evaluation Process
8 15
Exp1 a. Write a Java program to create an Applet that displays 12
student information and also set foreground and
backgrounds.

b. Write a Java Program to create an applet that scrolls a 14


message from left to right?

c. Write a Java program to create an Applet that reads 16


Employee information using parameters and displays
name of employee, designation, salary and tax.

Exp2 a. Write a java program to draw Lines, ovals, filled ovals 18


and arcs, filled arcs?

b. Write a java program to draw rectangle, filled


rectangle and rounded rectangle and filled rounded 20
rectangle with any two colors.

c. Write a java program to draw a smiley face? 22

2
AJP Lab Manual REVA University

Exp3 a. Write a Java Program that simulates a traffic light. The 23


program lets the user select one of three lights: red, yellow,
or green. When a radio button is selected, the light is
turned on, and only one light can be on at a time No light is
on when the program starts.

b. Write a Java Program to create multiple frames, which 25


create a Frame2 with a back button, such that when a user
click back button, Frame2 is closed and we see the Frame1
only?
Exp4 Write a Java Program a simple user form which reads the 27
name of a user and mail id in Text fields, select gender with
radio buttons, and selects some Known languages using
checkboxes, and also enters an address in a text area. After
filling details whenever a user press the “submit” button,
then displays all the information about the user input.

Exp5 Write a Java program that works as a simple calculator. 31


Use a grid layout to arrange buttons for the digits and for
the +, -, *, % operations. Add a text field to display the
resu1lt.

3
AJP Lab Manual REVA University

Exp 6 a. Write a Java program to implement Jcombo Box where 36


we can select state and language and displays elected items
using labels?
b.write a Java program to implement a JList where we can
select multiple courses and display them in Text area. 39

c.Write a Java program that creates a user interface to


perform integer divisions. The user enters two numbers in
the text fields, Num1 and Num2. The division of Num1 and
41
Num2 is displayed in the Result field when the Divide
button is clicked. If Num1 or Num2 were not an integer,
the program would throw a Number Format Exception. If
Num2 were Zero, the program would throw an Arithmetic
Exception Display the exception in a message dialog box.
Exp 7 a. Write a Java program to retrieve the information from 44
the given URL? (Note: Read the URL from Command Line
Arguments).
b. Write a Java program that implements as client/server
application. The client sends data to a server. The server 45

receives the data, uses it to produce a result, and then


sends the result back to the client. The client displays the
result on the console. For ex: The data sent from the client
is the radius of a circle, and the result produced by the
server is the area of the circle. (Use java.net)

a. Write a java program to create a sample TCP chat 48


application where client and server can chat with each
Exp 8
other?
51
b. Write a java program to perform a simple conversation
with UDP model?

4
AJP Lab Manual REVA University

Exp 9 a. Write a java program to create a bean that counts the 54


number of mouse clicks?
b. Write a java program to create a bean that counts the 55
number of button clicks?
c. Write a Java program to create a bean that display 56
employee name, salary, designation and company?
Exp 10 a. Write a servlet program to create a simple servlet and 58
test it?

b. Write a servlet program to read the client request 59


parameters.

Additional question 61

5
AJP Lab Manual REVA University

VISION OF THE UNIVERSITY

• “REVA University aspires to become an innovative university by developing


excellent human resources with leadership qualities, ethical and moral values,
research culture and innovative skills through higher education of global
standards”.
MISSION OF THE UNIVERSITY

• To create excellent infrastructure facilities and state-of-the-art laboratories and


incubation centers
• To provide student-centric learning environment through innovative pedagogy
and education reforms
• To encourage research and entrepreneurship through collaborations and extension
activities
• To promote industry-institute partnerships and share knowledge for innovation
and development
• To organize society development programs for knowledge enhancement in thrust
areas
• To enhance leadership qualities among the youth and enrich personality traits,
promote patriotism and moral values

VISION OF THE SCHOOL


To produce excellent quality technologists and researchers of global standards in
computing and Information technology who have potential to contribute to the
development of the nation and the society with their expertise, skills, innovative
problem-solving abilities, strong moral and ethical values.
MSSION OF THE SCHOOL

• To create state of the art computing labs infrastructure and research facilities in
information technology.
• To provide student-centric learning environment in Computing and Information
technology through innovative pedagogy and education reforms.
• To encourage research, innovation and entrepreneurship in computing and
information technology through industry/academia collaborations and extension
activities
• Organize programs through club activities for knowledge enhancement in thrust
areas of information technology.
• To enhance leadership qualities among the youth and enrich personality traits,
promote patriotism, moral and ethical values.
6
AJP Lab Manual REVA University

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1: Demonstrate technical skills, competency in AI & ML and exhibit team


management capability with proper communication in a job environment.

PEO2: Support the growth of economy of a country by starting enterprise with a


lifelong learning attitude.

PEO3: Carry out research in the advanced areas of AI & ML and address the basic
needs of the society.

PROGRAM SPECIFIC OUTCOMES (PSOs)

On successful completion of the programme, the graduates of B.Tech. AIML


programme will be able to:

•PSO-1 Demonstrate the knowledge of human cognition, Artificial Intelligence,


Machine Learning and data engineering for designing intelligent systems.

• PSO-2 Apply computational knowledge and project development skills to provide


innovative solutions.

• PSO-3 Use tools and techniques to solve problems in AI & ML.

7
AJP Lab Manual REVA University

PROGRAM OUTCOMES (POs)

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multi-disciplinary environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

8
AJP Lab Manual REVA University

ADVANCEDJAVAPROGRAMMINGLAB
OBJECTIVE:
❖ To create a fully functional window-based applications. To develop GUI
applications like Calculator, Notepad, Simple user forms, and designing and
implementing Component based application like Jelly Beans, Color bean, and
also designing of server-side pages, client server interactions with TCP.
OUTCOMES:
❖ Student can able to Designing of window-based applications.
❖ Studentcanabletocreateaclientandservercommunicationusingnetpackage.
❖ Student can able to design reusable software components using javabeans.
❖ Able to develop server-side programming.
❖ Able to develop the dynamic web pages using JSP.

CO-PO MAPPING:
CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 2 1 1 1 2 2 3 2 1
CO2 2 1 2 2 2 1 2 2
CO3 2 3 1 1 1 2 2 1
CO4 2 2 2 1 2 3 2
CO5 2 2 2 2 1 2 1

1. Lab Requirements:
• Simple Editor Note pad or other editor tools like Editplus or notepad++.
• A web browser IE/Firefox/chrome.
• Apache Tomcat webserver.
• JVM (Java virtual machine) must be installed on your system
• BDK (Bean development kit) must also be installed

2. Lab Requirements Hardware:

Following are the required hardware and software for this lab, which is available in the
laboratory.
Minimum System requirements:
• Processors: Intel Atom® processor or Intel® Core™ i3 processor.
• Disk space: 1 GB.
• Operating systems: Windows* 7 or later, macOS, and Linux.
• Python* versions: 2.7.X, 3.6.X.,3.8.X

3. Guidelines to Students
➢ Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care. Any
damage caused is punishable.
➢ Students are required to carry their observation / programs book with completed exercises
while entering the lab.
➢ Students are supposed to occupy the machines allotted to them and are not supposed to
talk or make noise in the lab. The allocation is put up on the lab noticeboard.

9
AJP Lab Manual REVA University

➢ Labcanbeusedinfreetime/lunchhoursbythestudentswhoneedtousethesystemsshouldtakepri
orpermissionfromthe lab in-charge.
➢ Lab records need to be submitted on or before date of submission.
➢ Students are not supposed to use flash drives.

4. Instructions to maintain the record


• Before start of the first lab they have to buy the record and bring the record to the lab.
• Regularly (Weekly) update the record after completion of the experiment and get it corrected
with concerned lab in-charge for continuous evaluation.
• In case the record is lost inform the same day to the faculty in charge and get the new record
within 2 days the record has to be submitted and get it corrected by the faculty.
• If record is not submitted in time or record is not written properly, the evaluation marks (5M)
will be deducted.

5. General laboratory instructions


1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with: a. Laboratory observation notes with all the
details (Problem statement, Aim, Algorithm, Procedure, Program, Expected Output, etc.,) filled in
for the lab session. b. Laboratory Record updated up to the last session experiments and other
utensils (if any) needed in the lab. c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty. 5. Execute your task in the laboratory, and record the results /
output in the lab observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high-end branded systems, which should
be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately

Conduction of Practical Examination:


1. All laboratory experiments (No. 1 to No. 10) are included for the syllabus of practical
examination.
2. Students are allowed to pick one experiment from the lot.
3. Strictly follow the instructions as printed on the cover page of answer script.
4. Marks distribution:
Procedure + Conduction + Viva: 08 + 35 +07 = 50 Marks

10
AJP Lab Manual REVA University

Change of experiment is allowed only once and marks allotted to the procedure part to be made
zero.

CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 2 1 1 1 2 2 3 2 1
CO2 2 1 2 2 2 1 2 2
CO3 2 3 1 1 1 2 2 1
CO4 2 2 2 1 2 3 2
CO5 2 2 2 2 1 2 1

WEEKWISE EVALUATION OF EACH PROGRAM

INTERNAL ASSESSMENT EVALUATION


(End of Semester)
Sl No ACTIVITY MARKS
01 Procedure 7
02 Conduction 8
03 Viva Voce 5
Total 20

FINAL INTERNAL ASSESSMENT CALCULATION


Sl. No ACTIVITY MARKS
01 Average of weekly Entries 30
02 Internal Assessment Reduced to 20
Total 50

11
AJP Lab Manual REVA University

1 a. Write a Java program to create an Applet that displays student information and
also set foreground and backgrounds.
SOURCE
import java.awt.*;
import java.applet.*;

/*<Appletcode="MsgApplet", height="150", width="300">

</Applet>*/

public class MsgApplet extends Applet {

String name, branch, sec;


int rno;

public void init() {


// Initialize the variables
name = "abc";
branch = "CSE";
sec = "A";
rno = 500;

// Set the background and foreground colors


setBackground(Color.gray);
setForeground(Color.green);
}

public void paint(Graphics g) {


// Display the student's name
g.drawString("Name of Student: " + name, 50, 40);

// Display the branch


g.drawString("BRANCH: " + branch, 50, 60);

// Display the roll number


g.drawString("RNO: " + rno, 50, 70);

// Display the section


g.drawString("SECTION: " + sec, 50, 80);
}
}

12
AJP Lab Manual REVA University

Output:

In cmd prompt:

D:\cse>javac MsgApplet.java

D:\cse>appletviewer

MsgApplet.java

13
AJP Lab Manual REVA University

1. b. Write a Java Program to create an applet that scrolls a message from left to right?

import java.awt.*;
import java.applet.*;

/*<applet code="Scroll" height=200 width=500></applet>*/


public class Scroll extends Applet implements Runnable {

String msg = "*****MovingText*****";


Thread t = null;
int l;
boolean flag;

public void init() {


setBackground(Color.pink);
setForeground(Color.blue);
}

public void start() {


t = new Thread(this);
flag = false;
t.start();
}

public void run() {


char ch;
for (;;) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
l = msg.length();
msg = msg.substring(1, l);
msg += ch;
if (flag)
break;
} catch (InterruptedException e) {
}
}
}

public void stop() {


flag = true;
t = null;
}

14
AJP Lab Manual REVA University

public void paint(Graphics g) {


g.drawString(msg, 120, 80);
}
}

Output:

15
AJP Lab Manual REVA University

1. c. Write a Java program to create an Applet that reads Employee information


using parameters and displays name of employee, designation, salary and tax.

SOURCE:

import java.awt.*;
import java.applet.*;

/*<applet code="EmpDetails" height=100 width=200>

<param name="e1" value="Ram">

<param name="e2" value="Manager">

<param name="e3" value=160000.50>

</applet>
*/

public class EmpDetails extends Applet {

String name, desg, str;


float sal, tax;

public void start() {


// Get the values of the parameters passed to the applet
name = getParameter("e1");
desg = getParameter("e2");
str = getParameter("e3");
sal = Float.parseFloat(str);

// Calculate the tax based on the salary


caltax(sal);
}

public void caltax(float sal) {


if (sal <= 100000)
tax = 0.0f;
else if (sal > 100000 && sal <= 200000)
tax = sal * 0.01f;
else
tax = sal * 0.02f;
}

public void paint(Graphics g) {

16
AJP Lab Manual REVA University

// Display the employee details and tax information


g.drawString("Name of Emp: " + name, 20, 30);
g.drawString("Designation: " + desg, 20, 60);
g.drawString("Salary: " + sal, 20, 90);
g.drawString("Tax: " + tax, 20, 120);
}
}

OUTPUT:

17
AJP Lab Manual REVA University

2. a. Write a java program to draw Lines, ovals, filled ovals and arcs, filled arcs?

SOURCE:

import java.awt.*;
import java.applet.*;

/*<Applet code="TwoA", height="300", width="300"></Applet>*/


public class TwoA extends Applet {

public void paint(Graphics g) {

// Draw a vertical line


g.drawLine(20, 0, 20, 40);

// Draw a horizontal line


g.drawLine(0, 20, 40, 20);

// Draw an oval outline


g.drawOval(40, 40, 100, 50);

// Set the color to green and fill the oval


g.setColor(Color.green);
g.fillOval(140, 40, 100, 50);

// Draw a larger oval outline


g.drawOval(40, 140, 100, 100);

// Set the color to orange and fill the oval


g.setColor(Color.orange);
g.fillOval(140, 140, 100, 100);

// Draw an arc
g.drawArc(40, 240, 50, 50, 0, -180);

// Draw another arc


g.drawArc(100, 265, 50, 50, 0, 180);
}
}

18
AJP Lab Manual REVA University

OUTPUT:

19
AJP Lab Manual REVA University

2. b. Write a java program to draw rectangle, filled rectangle, rounded rectangle and
filled rounded rectangle with any two colors?

SOURCE:

import java.awt.*;
import java.applet.*;

/*<Applet code="TwoB" height="300" width="300"></Applet>*/


public class TwoB extends Applet {

public void paint(Graphics g) {


// Draw a rectangle with a black outline
g.drawRect(20, 0, 100, 50);

// Set the color to green and fill a rectangle


g.setColor(Color.green);
g.fillRect(140, 0, 100, 50);

// Draw a rounded rectangle with a black outline


g.drawRoundRect(20, 70, 100, 50, 10, 10);

// Set the color to blue and fill a rounded rectangle


g.setColor(Color.blue);
g.fillRoundRect(140, 70, 100, 50, 20, 20);

// Draw a rectangle with a black outline


g.drawRect(20, 140, 100, 100);

// Set the color to red and fill a rectangle


g.setColor(Color.red);
g.fillRect(140, 140, 100, 100);
}
}

20
AJP Lab Manual REVA University

OUTPUT:

21
AJP Lab Manual REVA University

2. c. Write a java program to draw a smiley face

SOURCE:

import java.awt.*;
import java.applet.*;

/*<Applet code="TwoC" height="300" width="300"></Applet>*/


public class TwoC extends Applet {

public void paint(Graphics g) {

// Draw a rectangle
g.drawRect(40, 40, 200, 200);

// Set the color to yellow


g.setColor(Color.yellow);

// Draw a circle
g.drawOval(90, 70, 80, 80);

// Draw two small dots


g.drawOval(110, 95, 5, 5);
g.drawOval(145, 95, 5, 5);

// Draw a line
g.drawLine(130, 95, 130, 115);

// Draw an arc
g.drawArc(113, 115, 35, 20, 0, -180);
}
}
OUTPUT:

22
AJP Lab Manual REVA University

3. a. Write a JavaProgramthatimulatesatrafficlight.Theprogramletstheuserselect one


of three lights: red, yellow, or green. When a radio button is selected, the light is
turned on, and only one light can be on at a time No light is on when the program
starts.

SOURCE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code="TrafficLights" height=250 width=500></applet>*/


public class TrafficLights extends Applet implements ItemListener {
CheckboxGroup cbg;
Checkbox c1, c2, c3;
TextField t1;

public void init() {


cbg = new CheckboxGroup();
c1 = new Checkbox("Red", cbg, false);
c2 = new Checkbox("Yellow", cbg, false);
c3 = new Checkbox("Green", cbg, false);
t1 = new TextField(30);
add(c1);
add(c2);
add(c3);
add(t1);
}

public void start() {


c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}

public void paint(Graphics g) {


g.setColor(Color.red);
g.drawOval(10, 50, 30, 30);
g.setColor(Color.yellow);
g.drawOval(10, 100, 30, 30);
g.setColor(Color.green);
g.drawOval(10, 150, 30, 30);

String s1 = cbg.getSelectedCheckbox().getLabel();
if (s1 == "Red") {
g.setColor(Color.red);
g.fillOval(10, 50, 30, 30);
23
AJP Lab Manual REVA University

t1.setText("Stop the Vehicle");


} else if (s1 == "Yellow") {
g.setColor(Color.yellow);
g.fillOval(10, 100, 30, 30);
t1.setText("Be Ready to Go");
} else if (s1 == "Green") {
g.setColor(Color.green);
g.fillOval(10, 150, 30, 30);
t1.setText("You Can Go Now");
}
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}
}

Output:

24
AJP Lab Manual REVA University

3. b. Write a Java Program to create multiple frames, which create Frame2 with a back button,
such that when a user click back button, Frame 2 is closed and we see the Frame1 only?

SOURCE:
Saveas: MyFrame1.java
import java.awt.*;
import java.awt.event.*;

public class MyFrame1 extends Frame implements ActionListener {


Button b1, b2;

MyFrame1() {
b1 = new Button("Next"); // Create a button with label "Next"
add(b1); // Add the button to the frame

b2 = new Button("cancel"); // Create a button with label "cancel"


add(b2); // Add the button to the frame

b1.addActionListener(this); // Add an action listener to button b1


b2.addActionListener(this); // Add an action listener to button b2
}

public void actionPerformed(ActionEvent ae) {


if (b1 == ae.getSource()) { // Check if button b1 is the source of the action event
MyFrame2 f1 = new MyFrame2(); // Create an instance of MyFrame2
f1.setSize(100, 100); // Set the size of the frame
f1.setVisible(true); // Make the frame visible
f1.setTitle("secondFrame"); // Set the title of the frame
}
}

public static void main(String args[]) {


MyFrame1 f = new MyFrame1(); // Create an instance of MyFrame1
f.setTitle("first frame"); // Set the title of the frame
f.setSize(500, 500); // Set the size of the frame
f.setVisible(true); // Make the frame visible
}
}

25
AJP Lab Manual REVA University

Saveas: MyFrame2.java

class MyFrame2 extends Frame implements ActionListener {


Button b1;

MyFrame2() {
// Creating a new button with the label "Back"
b1 = new Button("Back");
// Adding the button to the frame
add(b1);
// Registering the frame as the ActionListener for the button
b1.addActionListener(this);
}

public void actionPerformed(ActionEvent ae) {


// Disposing the frame when the button is clicked
this.dispose();
}}
Output:

26
AJP Lab Manual REVA University

4.Write a Java Program a simple user form which reads the name of a user and mail id in
Text fields, select gender with radio buttons, and selects some Known languages using
checkboxes, and also enters an address in a text area. After filling details whenever a user
press the “submit” button, then displays all the information about the user input.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<Applet code="us" height="525" width="230">


</Applet>*/
public class us extends Applet implements ActionListener, ItemListener {
Label ad, lo, l1, l2, l3, pa, gn, dob;
TextField fn, mn, ln, ps;
Choice w, l, d, m, y;
Button b1;
TextArea t;

public void init() {


setLayout(new FlowLayout(FlowLayout.LEFT, 3, 3));
l1 = new Label("FIRST NAME :", Label.LEFT);
l2 = new Label("MIDDLE NAME:", Label.LEFT);
l3 = new Label("LAST NAME :", Label.LEFT);
pa = new Label("PASSWORD :", Label.LEFT);
fn = new TextField(10);
mn = new TextField(10);
ln = new TextField(10);
ps = new TextField(10);
ps.setEchoChar('*');
gn = new Label("GENDER", Label.LEFT);
w = new Choice();
w.add(" ");
w.add("MALE");
w.add("FEMALE");
lo = new Label(" LANGS", Label.LEFT);
l = new Choice();
l.add("");
l.add("Telugu");
l.add("English");
l.add("Tamil");
l.add("Kannada");
dob = new Label("DOB:", Label.LEFT);
d = new Choice();
27
AJP Lab Manual REVA University

d.add("");
for (int i = 1; i <= 31; i++) {
d.add("" + i);
}
m = new Choice();
m.add("");
String md[] = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JULY", "AUG",
"SEP", "OCT", "NOV", "DEC" };
for (int j = 0; j <= 11; j++) {
m.add("" + md[j]);
}
y = new Choice();
y.add(" ");
for (int k = 1980; k <= 2999; k++) {
y.add("" + k);
}
ad = new Label("\nADRS:", Label.LEFT);
t = new TextArea(5, 10);
b1 = new Button("SUBMIT");
add(l1);
add(fn);
add(l2);
add(mn);
add(l3);
add(ln);
add(pa);
add(ps);
add(gn);
add(w);
add(lo);
add(l);
add(dob);
add(d);
add(m);
add(y);
add(ad);
add(t);
add(b1);
}

public void start() {


fn.addActionListener(this);
28
AJP Lab Manual REVA University

mn.addActionListener(this);
ln.addActionListener(this);
ps.addActionListener(this);
b1.addActionListener(this);
}

public void actionPerformed(ActionEvent ae) {


if (b1 == ae.getSource()) {
}
repaint();
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}

public void paint(Graphics g) {


Font f1 = new Font("Arial Black", Font.PLAIN, 10);
g.setFont(f1);
g.setColor(Color.yellow);
g.drawRoundRect(0, 305, 175, 225, 45, 45);
g.fillRoundRect(0, 305, 175, 225, 45, 45);
g.setColor(Color.black);
g.drawString("first name :" + fn.getText(), 5, 345);
g.drawString("middle name :" + mn.getText(), 5, 365);
g.drawString("last name :" + ln.getText(), 5, 385);
g.drawString("password :" + ps.getText(), 5, 405);
g.drawString("GENDER:" + w.getSelectedItem(), 5, 425);
g.drawString("LAGS :" + l.getSelectedItem(), 5, 445);

g.drawString("DOB:" + d.getSelectedItem() + "_" + m.getSelectedItem() + "_" +


y.getSelectedItem(), 5, 465);
g.drawString("ADRS:" + t.getText(), 5, 485);
}
}

29
AJP Lab Manual REVA University

OUTPUT:

30
AJP Lab Manual REVA University

5. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the
resu1lt.

SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="Cal" width=300 height=300>
</applet>
*/

public class Cal extends Applet implements ActionListener {


String msg = " ";
int v1, v2, result;
TextField t1;
Button b[] = new Button[10];
Button add, sub, mul, div, clear, mod, EQ;
char OP;

public void init() {


Color k = new Color(120, 89, 90);
setBackground(k);
t1 = new TextField(10);
GridLayout gl = new GridLayout(4, 5);
setLayout(gl);

for (int i = 0; i < 10; i++) {


b[i] = new Button("" + i);
}

add = new Button("add");


sub = new Button("sub");
mul = new Button("mul");
div = new Button("div");
mod = new Button("mod");
clear = new Button("clear");
EQ = new Button("EQ");

31
AJP Lab Manual REVA University

t1.addActionListener(this);
add(t1);

for (int i = 0; i < 10; i++) {


add(b[i]);
}

add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);

for (int i = 0; i < 10; i++) {


b[i].addActionListener(this);
}

add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}

public void actionPerformed(ActionEvent ae) {


String str = ae.getActionCommand();
char ch = str.charAt(0);

if (Character.isDigit(ch))
t1.setText(t1.getText() + str);
else if (str.equals("add")) {
v1 = Integer.parseInt(t1.getText());
OP = '+';
t1.setText("");
} else if (str.equals("sub")) {
v1 = Integer.parseInt(t1.getText());
OP = '-';
32
AJP Lab Manual REVA University

t1.setText("");
} else if (str.equals("mul")) {
v1 = Integer.parseInt(t1.getText());
OP = '*';
t1.setText("");
} else if (str.equals("div")) {
v1 = Integer.parseInt(t1.getText());
OP = '/';
t1.setText("");
} else if (str.equals("mod")) {
v1 = Integer.parseInt(t1.getText());
OP = '%';
t1.setText("");
}

if (str.equals("EQ")) {
v2 = Integer.parseInt(t1.getText());
if (OP == '+')
result = v1 + v2;
else if (OP == '-')
result = v1 - v2;
else if (OP == '*')
result = v1 * v2;
else if (OP == '/')
result = v1 / v2;
else if (OP == '%')
result = v1 % v2;
t1.setText("" + result);
}

if (str.equals("clear")) {
t1.setText("");
}
}
}

33
AJP Lab Manual REVA University

OUTPUT:

34
AJP Lab Manual REVA University

35
AJP Lab Manual REVA University

6 a. Write a Java program to implement JcomboBox where we can select state and
language and display selected items using lables?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Import necessary packages

class TenA extends JFrame implements ItemListener {


JComboBox b1, b2; // Declare JComboBox variables
JLabel l1, l2; // Declare JLabel variables

TenA() {
Container c = getContentPane(); // Get the content pane
c.setLayout(null); // Set the layout to null

b1 = new JComboBox(); // Create a new JComboBox


b2 = new JComboBox(); // Create a new JComboBox

// Add items to the JComboBox


b1.addItem("Andhra");
b1.addItem("Karnataka");
b1.addItem("Maharastra");
b1.addItem("Tamilnadu");
b1.addItem("Kerala");

// Add items to the JComboBox


b2.addItem("Telugu");
b2.addItem("Tamil");
b2.addItem("Malayalam");
b2.addItem("Marati");
b2.addItem("Kannada");

b1.setBounds(100, 50, 100, 40); // Set the bounds of b1


b2.setBounds(200, 50, 100, 40); // Set the bounds of b2

c.add(b1); // Add b1 to the container


c.add(b2); // Add b2 to the container

l1 = new JLabel("State"); // Create a new JLabel


l1.setBounds(100, 200, 200, 40); // Set the bounds of l1
c.add(l1); // Add l1 to the container

l2 = new JLabel("Language"); // Create a new JLabel

36
AJP Lab Manual REVA University

l2.setBounds(150, 250, 200, 40); // Set the bounds of l2


c.add(l2); // Add l2 to the container

b1.addItemListener(this); // Add an item listener to b1


b2.addItemListener(this); // Add an item listener to b2
}

public void itemStateChanged(ItemEvent ie) {


String str = (String) b1.getSelectedItem(); // Get the selected item from b1
l1.setText("You selected: " + str); // Set the text of l1

str = (String) b2.getSelectedItem(); // Get the selected item from b2


l2.setText("You selected: " + str); // Set the text of l2
}

public static void main(String args[]) {


TenA t = new TenA(); // Create a new instance of TenA
t.setTitle("ComboBox"); // Set the title of the frame
t.setVisible(true); // Set the frame to be visible
t.setSize(200, 200); // Set the size of the frame
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the default close operation
}
}
OUTPUT:

37
AJP Lab Manual REVA University

38
AJP Lab Manual REVA University

6. b. Write a Java program to implement a JList where we can select multiple courses and
display them in Text area.
SOURCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

// The TenB class extends JFrame and implements ListSelectionListener


class TenB extends JFrame implements ListSelectionListener {
JList jl; // Create a JList object
JLabel l; // Create a JLabel object
Object arr[]; // Create an array to store selected values
String msg = ""; // Initialize an empty string to store the selected values

// Constructor
TenB() {
Container c = getContentPane();
c.setLayout(null);

String items[] = {"Java", "C#", "C++", "C"}; // Create an array of items for the JList
jl = new JList(items); // Initialize the JList with the items array
jl.setBounds(100, 50, 100, 100); // Set the position and size of the JList
c.add(jl); // Add the JList to the container

l = new JLabel(); // Initialize the JLabel


l.setBounds(50, 200, 400, 40); // Set the position and size of the JLabel
c.add(l); // Add the JLabel to the container

jl.addListSelectionListener(this); // Add a ListSelectionListener to the JList


}

// Method to handle list selection event


public void valueChanged(ListSelectionEvent le) {
arr = jl.getSelectedValues(); // Get the selected values from the JList
for (int i = 0; i < arr.length; i++)
msg += (String) arr[i]; // Concatenate the selected values into a string
l.setText("Selected: " + msg); // Set the text of the JLabel to display the selected values
msg = ""; // Reset the string to store the selected values
}

// Main method
public static void main(String args[]) {
TenB t = new TenB(); // Create an instance of the TenB class
t.setTitle("List"); // Set the title of the JFrame
t.setSize(200, 200); // Set the size of the JFrame

39
AJP Lab Manual REVA University

t.setVisible(true); // Make the JFrame visible


t.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Set the default close operation of
the JFrame
}
}

OUTPUT:

40
AJP Lab Manual REVA University

6.C. Write a Java program that creates a user interface to perform integer divisions.
The user enters two numbers in the text fields, Num1 and Num2. The division of Num1
and Num2 is displayedin the Result field when the Divide button is clicked. If Num1 or
Num2 were not an integer, the program would throw a Number Format Exception. If
Num2 were Zero, the program would throw an Arithmetic Exception Display the
exception in a message dialog box.
SOURCE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

/*<applet code="IntDivision" height=200 width=500></applet>*/


public class IntDivision extends Applet implements ActionListener {
TextField t1, t2, t3;
Label l1, l2, l3;
Button b1;

public void init() {


setBackground(Color.gray);
setForeground(Color.red);
t1 = new TextField(20);
t2 = new TextField(20);
t3 = new TextField(20);
l1 = new Label("Enter First Number:", Label.LEFT);
l2 = new Label("Enter Second Number:", Label.LEFT);
l3 = new Label("Result :", Label.LEFT);
b1 = new Button("Division");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
}

public void start() {


b1.addActionListener(this);
}

public void actionPerformed(ActionEvent ae) {


try {
int x = Integer.parseInt(t1.getText());
int y = Integer.parseInt(t2.getText());

41
AJP Lab Manual REVA University

String str = ae.getActionCommand();


if (str.equals("Division")) {
int div = x / y;
t3.setText(String.valueOf(div));
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please Enter the Correct Format");
} catch (ArithmeticException are) {
JOptionPane.showMessageDialog(null, "Please don't Enter the 2nd number as ZERO");
}
}}
OUTPUT:

42
AJP Lab Manual REVA University

43
AJP Lab Manual REVA University

7. a. Write a Java program to retrieve the information from the given URL (Note: Read the
URL from Command Line Arguments).
SOURCE:
import java.net.*;
import java.io.*;

class TwelveA {
public static void main(String args[]) throws Exception {
// Create a new URL object with the specified URL
URL hp = new URL("http://www.yahoo.com/index.html");
// Print the protocol of the URL
System.out.println("Get protocol: " + hp.getProtocol());
// Print the domain name of the URL
System.out.println("Get Domain name: " + hp.getHost());
// Print the port number of the URL
System.out.println("Port number: " + hp.getPort());
// Print the file path of the URL
System.out.println("File: " + hp.getPath());
// Print the external form of the URL
System.out.println("URL is: " + hp.toExternalForm());
// Print the file name of the URL
System.out.println("File name: " + hp.getFile());
}
}
OUTPUT:

44
AJP Lab Manual REVA University

7. b. Write a Java program that implements a simple client/server application. The


client sends data to a server. The server receives the data, uses it to produce a result,
and then sends the result back to the client. The client displays the result on the console.
For ex: The data sent from the client is the radius of a circle, and the result produced by
the server is the area of the circle. (Use java.net)
SOURCE:
CLIENT CODE:
import java.io.*;
import java.net.*;
import java.lang.*;

class TwelveB1 {
public static void main(String args[]) throws Exception {
// Create a server socket on port 888
ServerSocket ss = new ServerSocket(888);

// Accept incoming client connections


Socket s = ss.accept();

// Create a print stream to send data to the client


PrintStream ps = new PrintStream(s.getOutputStream());
System.out.println("Connection Established");

// Create a buffered reader to read data from the client


BufferedReader br1 = new BufferedReader(new
InputStreamReader(s.getInputStream()));

// Read the radius sent by the client


int r = Integer.parseInt(br1.readLine());
System.out.println("The radius received from the client is: " + r);

// Calculate the area of the circle


Double area = Math.PI * r * r;
System.out.println("The area is: " + area);

// Send the area back to the client


ps.println(area);

// Close the streams and sockets


ps.close();

45
AJP Lab Manual REVA University

br1.close();
ss.close();
s.close();
}
}

SERVERCODE:
import java.io.*;
import java.net.*;

class TwelveB2 {
public static void main(String args[]) throws Exception {
// Create a socket object and connect to the localhost on port 888
Socket s = new Socket("localhost", 888);

// Create a DataOutputStream object to send data through the socket


DataOutputStream dos = new DataOutputStream(s.getOutputStream());

// Create a BufferedReader object to read input from the user


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter radius:");
int r = Integer.parseInt(br.readLine());

// Send the radius to the server


dos.writeBytes("" + r);

// Create a BufferedReader object to read the response from the server


BufferedReader br1 = new BufferedReader(new InputStreamReader(s.getInputStream()));

// Read the area from the server's response


double area = Double.parseDouble(br1.readLine());

System.out.println("The area is: " + area);

// Close the BufferedReader and DataOutputStream objects


br1.close();
dos.close();
br.close();

// Close the socket


s.close();
}
}

46
AJP Lab Manual REVA University

Output:

47
AJP Lab Manual REVA University

8. a. Write a java program to create a sample TCP chat application where client and server
can chat with each other?
SOURCE:
CLIENTCODE:
import java.net.*;
import java.io.*;

class ThirteenA1 {
public static void main(String args[]) throws Exception {
// Create a server socket on port 888
ServerSocket ss = new ServerSocket(888);

// Accept incoming client connection


Socket s = ss.accept();

// Print a message to indicate that the connection is established


System.out.println("Connection established");

// Create a print stream to send data to the client


PrintStream ps = new PrintStream(s.getOutputStream());

// Create a buffered reader to read data from the client


BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

// Create a buffered reader to read data from the console


BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));

// Continuously read data from the client and send it back


while (true) {
String str = "", str1 = "";

// Read a line of data from the client


while ((str = br.readLine()) != null) {
System.out.println("" + str);

// Read a line of data from the console


str1 = br1.readLine();

// Send the data back to the client


ps.println(str1);
}
48
AJP Lab Manual REVA University

// Close the streams and sockets


ps.close();
br.close();
br1.close();
ss.close();
s.close();

// Exit the program


System.exit(0);
}
}
}
SERVERCODE:
import java.net.*;
import java.io.*;

class ThirteenA2 {
public static void main(String args[]) throws Exception {
// Create a socket object and connect to the server
Socket s = new Socket("localhost", 888);

// Create a DataOutputStream object to send data to the server


DataOutputStream dos = new DataOutputStream(s.getOutputStream());

// Create a BufferedReader object to read data from the server


BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

// Create a BufferedReader object to read input from the user


BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));

String str = "", str1 = "";

// Read input from the user until "exit" is entered


while (!(str1 = br1.readLine()).equals("exit")) {
// Send the user input to the server
dos.writeBytes(str1 + "\n");

// Read the response from the server


str = br.readLine();

49
AJP Lab Manual REVA University

// Print the response from the server


System.out.println("" + str);
}

// Close the streams and socket


dos.close();
br.close();
br1.close();
s.close();
}
}
Output:

50
AJP Lab Manual REVA University

8. b. Write a java program to perform a simple conversation with


UDP model
SOURCE:
CLIENT:
import java.net.*;
import java.io.*;

public class ThirteenB2 {


public static void main(String args[]) throws Exception {
// Get the local host address
InetAddress ia = InetAddress.getLocalHost();
// Create a DatagramSocket with port number 1024 and the local host address
DatagramSocket ds = new DatagramSocket(1024, ia);
// Initialize a string variable
String str1 = "";
// Create a BufferedReader to read input from the user
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));

// Read input from the user until "exit" is entered


while (!(str1 = br1.readLine()).equals("exit")) {
// Convert the input string to bytes
byte b[] = str1.getBytes();

// Create a DatagramPacket with the input bytes, the local host address, and port number 8
DatagramPacket out = new DatagramPacket(b, b.length, ia, 8);

// Send the packet to the server


ds.send(out);
// Print the sent message
System.out.println("Sending to server...: " + (new String(b)));
// Create a byte array to receive the response from the server
byte buff[] = new byte[50];

// Create a DatagramPacket to receive the response


DatagramPacket in = new DatagramPacket(buff, buff.length);

// Receive the response from the server


ds.receive(in);
// Print the received message
System.out.println("Received from server...: " + new String(buff));
}

// Close the DatagramSocket


ds.close();
}}
51
AJP Lab Manual REVA University

SERVER:
import java.net.*;
import java.io.*;

class ThriteenB1 {
public static void main(String args[]) throws Exception {
// Create a DatagramSocket object to listen for incoming datagrams on port 8
DatagramSocket ds = new DatagramSocket(8);

// Create a byte array to store the received data


byte b[] = new byte[50];

// Create a DatagramPacket object to receive the data


DatagramPacket in = new DatagramPacket(b, b.length);

// Receive the data from the client


ds.receive(in);

// Print the received data


System.out.println("in server_receiving from client: " + new String(b));

// Create a response message to send back to the client


String str = "hello client";
byte buff[] = str.getBytes();

// Print the response message


System.out.println("sending address to client: " + new String(buff));

// Create a DatagramPacket object to send the response message


DatagramPacket out = new DatagramPacket(buff, buff.length, in.getAddress(), in.getPort());

// Send the response message to the client


ds.send(out);

// Close the DatagramSocket


ds.close();
}}

52
AJP Lab Manual REVA University

OUTPUT:

53
AJP Lab Manual REVA University

9. a. Write a java program to create a bean that counts the number of mouse clicks?
SOURCE:
import java.beans.*;
import java.io.Serializable;
import java.awt.*;
import java.awt.event.*;
public class Mouseclick extends Canvas {
private int count = 0;
public Mouseclick() {
// Add a mouse listener to the canvas
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
count++; // Increment the count when the mouse is pressed
repaint(); // Redraw the canvas
}
};
setSize(50, 80); // Set the size of the canvas
setBackground(Color.green); // Set the background color of the canvas
setForeground(Color.red); // Set the foreground color of the canvas
}
public void paint(Graphics g) {
// Draw the number of mouse clicks on the canvas
g.drawString("Number of Mouse Clicks: " + count, 40, 60);
}
}

OUTPUT:

54
AJP Lab Manual REVA University

9. b. Write a java program to create a bean that counts the number of button clicks?
SOURCE:
import java.awt.*;
import java.awt.event.*;
public class fourteenB extends Panel implements ActionListener {
int count;
Button but;
public fourteenB() {
count = 0;
setSize(200, 100);
but = new Button("Click me"); // Creating a button with the label "Click me"
but.addActionListener(this); // Adding an action listener to the button
add(but); // Adding the button to the panel
}
public void actionPerformed(ActionEvent e) {
count++; // Incrementing the count variable
repaint(); // Calling the repaint method to update the panel
}
public void paint(Graphics g) {
Dimension d = getSize();
Font f = new Font("Courier", Font.BOLD, 30);
int h = d.height;
int w = d.width;
g.setColor(Color.pink);
g.fillRect(0, 0, w - 1, h - 1);
g.setFont(f);
g.setColor(new Color(0, 0, 0));
g.drawString("Click count = " + count, 50, 50); // Displaying the click count on the panel
}}
Output:

55
AJP Lab Manual REVA University

9. c. Write a Java program to create a bean that display employe ename, salary, designation and
company?
SOURCE:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;

public class Emp extends Canvas {


private String ename, designation, address;
private double salary;
private int age;

public Emp() {
ename = "Hemanth";
designation = "DataBaseManager";
address = "kurnool";
salary = 50000;
age = 24;
}
public void setEname(String name) {
ename = name;
}
public void setDesignation(String desg) {
designation = desg;
}
public void setAddress(String adr) {
address = adr;
}
public void setSalary(double sal) {
salary = sal;
}
public void setAge(int ag) {
age = ag;
}
public String getEname() {
return ename;
}
public String getDesignation() {
return designation;
}
public double getSalary() {
return salary;
}
public int getAge() {
return age;
56
AJP Lab Manual REVA University

}
public void paint(Graphics g) {
g.drawString("Name:" + ename, 20, 20);
g.drawString("Address:" + address, 20, 40);
g.drawString("Designation:" + designation, 20, 70);
g.drawString("Salary:" + salary, 20, 80);
}
}
OUTPUT:

57
AJP Lab Manual REVA University

10 a. Write a Java Program to create a simple Servlet and test it on to mcatserver?


FirstServlet.java:
import java.io.*;
import javax.servlet.*;
public class FirstServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
// Comment: Printing the HTML tags for the webpage
pw.println("<html><head><title>First Servlet</title></head>");
pw.println("<body><center><h1>This Message came from a servlet</h1>");
pw.println("</center></body></html>");
pw.close(); }}
Web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:

58
AJP Lab Manual REVA University

10. b. Write a Java Program to create a Servlet that Reads Request Parameters and
display their values?

<html>
<head>
<title>ServletParameters</title>
</head>
<body>
<center>
<formname="form1"method="POST"action="http://localhost:9401/rpar/rparam">
<table>
<tr>
<td><b>Employee</td>
<td><inputtype="text"name="ename"value=""></td>
</tr>
<tr>
<td><b>Id</td>
<td><inputtype="text"name="id"value=""></td>
</tr>
<tr>
<td><inputtype="submit"value="submit"></td>
<td><inputtype="reset"value="clear"></td>
</tr>
</table>
</form>
</center>
</body>
</html>

Rparam.java
import java.io.*;
import java.util.*;
import javax.servlet.*;

public class Rparam extends GenericServlet {


public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();

59
AJP Lab Manual REVA University

// Loop through all the parameter names


Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String pname = (String) e.nextElement();
// Print the parameter name in bold
pw.println("<b>" + pname + "=");
// Get the parameter value
String pvalue = req.getParameter(pname);
// Print the parameter value in bold
pw.println("<b>" + pvalue);
}
pw.close();
}}

Web.xml:
<web-app>
<servlet>
<servlet-name>rp</servlet-name>
<servlet-class>Rparam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rp</servlet-name>
<url-pattern>/rparam</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:

60
Additional question and Answers

Q1-What is the Java Features?


A1
1.Compiled and Interpreted
2.Platform-Independent and Portable
3.Object Oriented
4.Robust 5.Distributed
6.Simple, Small andFamiliar7.Multithreadedandinteractive8.HighPerformance9.Dynamic and
Extensible
Q2-HowJava DiffersFromC?
A2-1.Java does not include the C unique statement keywords goto, size of, andtype
def.2.Javadoes notcontainthedatatype struct,unionand enum.
3.Javadoesnot
definethetypemodifierskeywordsauto,extern,register,signed,andunsigned.4.Javadoes
notsupportan explicitpointertype.
Q3-HowJava DiffersFromC++ ?
A3-1.javadoesnot supportoperatoroverloading.
2. Javadoesnothavetemplateclasses asin C++.
3.Javadoesnotmultipleinheritanceofclasses.Thisisaccomplishedusinganewfeaturecalled“interface
”.Q4-WhatisThe Java Components?
A4-1.Object and Classes 2.Data Abstraction and Encapsulation 3.Inheritance 4.Polymorephism
5.DynamicBinding6.MessageCommunication.
Q5-WhatistheJava Developmentkit(JDK)?
A5-1.appletviewer(for viewing Java applets) 2.javac(Java compiler)3.java(Java interpreter)
4.javap(Javadisassembler) 5.javah(for C header files) 6.javadoc(for creating HTML
documents) 7.jdb(Java debugger)Q6-WhatistheVariables?
A6- A variable is an identifier that denotes a storage location used to store a
data value.Q7-WhatareClass?
A7- Class is a template for multiple objects with similar features and it is a blue print for objects.
It defines atypeofobjectaccording to thedatatheobjectcanhold andtheoperationsthe
objectcanperform.
Q8-WhatarePrimitivedatatypes?

61
A8- Primitive data types are 8 types and they are: byte, short, int, long, float, double,
boolean, char.Q9-Whatisthemethodoverloading.?
A9- Function with same name but different argument perform different task known as
methodoverloading.Q10-Whatareinnerclass and anonymousclass?
A10- Inner class : classes defined in other classes, including those defined in methods are called
innerclasses. An inner class can have any accessibility including private. Anonymous class
:Anonymous class is aclass defined inside a method without a name and is instantiated and declared
in the same place and cannothaveexplicitconstructors.

62

You might also like