Ec8003 Scheme
Ec8003 Scheme
Ec8003 Scheme
EC8003/4
CORE JAVA
1
EC8003/4
IV/IV B.Tech. DEGREE EXAMINATION, APRIL,2017
Eighth Semester
CORE JAVA
SCHEME CUM EVALUATION SET
Max. Marks: 70
PART-A
(10*1=10M)
a. Define JVM.
Ans.: The Java Virtual Machine (JVM) is the runtime engine of the Java Platform,
which allows any program written in Java or other language compiled into Java
bytecode to run on any computer that has a native JVM.
// Constructors
clsName(cparam1)
{
// body of constructor
}
:
:
clsName(cparamN)
{
// body of constructor
}
// Methods
rType1 methodName1(mParams1)
{
// body of method
2
}
:
:
rTypeN methodNameN(mParamsN)
{
// body of method
}
}
3
i. Explain about JComboBox class.
Ans.: JComboxBox is a Swing component that renders a drop-down list of choices and lets
the user selects one item from the lis
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.
PART-B (4*15=60M)
UNIT-I
Scanner scan;
int matrix1[][], matrix2[][], multi[][];
int row, column;
void create() {
System.out.println("Matrix Multiplication");
4
// First Matrix Creation..
System.out.println("\nEnter number of rows & columns");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
matrix1[i][j] = scan.nextInt();
}
}
matrix2[i][j] = scan.nextInt();
}
}
}
void display() {
System.out.print("\t" + matrix1[i][j]);
}
System.out.println();
}
5
System.out.print("\t" + matrix2[i][j]);
}
System.out.println();
}
}
void multi() {
System.out.print("\t" + multi[i][j]);
}
System.out.println();
}
}
}
class MainClass {
obj.create();
obj.display();
obj.multi();
}
}
1. b. Write a Jva program to print prime numbers below the given range n.
7M
Ans.:
import java.util.Scanner;
class prime
{
public static void main(String[] args)
{
6
int n,p;
Scanner s=new Scanner(System.in);
System.out.println(Enter upto which number prime numbers are
needed);
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
(or)
2. a. Explain different types of constructors with suitable examples. 8M
Ans.:
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
7
Java Default Constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
} }
8
Example of parameterized constructor:
class Student{
int id;
String name;
id = i;
name = n;
s1.display();
s2.display();
System.out.println(text);
}
}
9
public static void main(String args[]) {
System.out.println(text);
}
}
if(text.isEmpty());
else
System.out.println(text.length());
}
}
System.out.println(ans1);
System.out.println(ans2);
System.out.println(ans3);
System.out.println(ans4);
}
}
10
int indexOf = text.indexOf('e');
int lastIndexOf = text.lastIndexOf('e');
System.out.println("\n" + val1);
System.out.println(val2);
System.out.println(val3);
}
}
UNIT-II
Ans.:
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
11
Ways to achieve Abstaction
Interface (100%)
A class that is declared as abstract is known as abstract class. It needs to be extended and
its method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
obj.run();
12
3. b. Explai how Access protection is handled in packages. 7M
Ans.:
Access Protection in Packages
Access modifiers define the scope of the class and its members (data and methods). For
example, private members are accessible within the same class members
(methods). Java provides many levels of security that provides the visibility of members
(variables and methods) within the classes, subclasses, and packages.
Packages are meant for encapsulating, it works as containers for classes and other
subpackages. Class acts as containers for data and methods. There are four categories,
provided by Java regarding the visibility of the class members between classes and
packages:
The three main access modifiers private, public and protected provides a range of ways to
access required by these categories.
Simply remember, private cannot be seen outside of its class, public can be access from
anywhere, and protected can be accessible in subclass only in the hierarchy.
A class can have only two access modifier, one is default and another is public. If the class
has default access then it can only be accessed within the same package by any other code.
But if the class has public access then it can be access from any where by any other code.
Example:
//PCKG1_ClassOne.java
package pckg1;
public class PCKG1_ClassOne{
int a = 1;
private int pri_a = 2;
protected int pro_a = 3;
public int pub_a = 4;
public PCKG1_ClassOne() {
System.out.println("base class constructor called");
System.out.println("a = " + a);
System.out.println("pri_a = " + pri_a);
13
System.out.println("pro_a "+ pro_a);
System.out.println("pub_a "+ pub_a);
}
}
The above file PCKG1_ClassOne belongs to package pckg1, and contains data members
with all access modifiers.
//PCKG1_ClassTwo.java
package pckg1;
class PCKG1_ClassTwo extends PCKG1_ClassOne {
PCKG1_ClassTwo() {
System.out.println("derived class constructor called");
System.out.println("a = " + a);
II accessible in same class only
II System.out.println("pri_a = " + pri_a);
System.out.println("pro_a "+ pro_a);
System.out.println("pub_a = + pub_a);
}
}
package pckg1;
class PCKG1_ClassInSamePackage {
PCKG1_ClassInSamePackage() {
PCKG1_ClassOne co = new PCKG1_ClassOne();
System.out.println("same package class constructor called");
System.out.println("a = " + co.a);
II accessible in same class only
II System.out.println("pri_a = " + co.pri_a);
System.out.println("pro_a "+ co.pro_a);
System.out.println("pub_a = " + co.pub_a);
}
}
14
The above file PCKG1_ClassInSamePackage belongs to package pckg1, and having an
instance of PCKG1_ClassOne.
package PCKG1;
//Demo package PCKG1
public class DemoPackage1 {
public static void main(String ar[]) {
PCKG1_ClassOne obl = new PCKG1_ClassOne();
PCKG1_ClassTwo ob2 = new PCKG1_ClassTwo();
PCKG1_ClassInSamePackage ob3 = new PCKG1_ClassxnSamePackage();
}
}
The above file DemoPackageI belongs to package pckgI, and having an instance of all
classes in pckg1.
package pckg2;
class PCKG2_ClassOne extends PCKG1.PCKG1_ClassOne {
PCKG2_ClassOne() {
System.out.println("derived class of other package constructor
called");
II accessible in same class or same package only
II System.out.println("a = " + a);
II accessible in same class only
II System.out.println("pri_a = " + pri_a);
System.out.println("pro_a = " + pro_a);
System.out.println("pub_a = " + pub_a);
}
}
The above file PCKG2_ClassOne belongs to package pckg2. extends PCKG I_ClassOne,
which belongs to PCKG1, and it is trying to access data members of the class
PCKGI_ClassOne.
IIPCKG2_ ClassInOtherPackage
package pckg2;
class PCKG2_ClassInOtherPackage {
PCKG2_ClassInOtherpackage() {
15
PCKG1.PCKG1_ClassOne co = new PCKG1.PCKG1_ClassOne();
System.out.println("other package constructor");
II accessible in same class or same package only
II System.out.println("a ,= " + co.a);
II accessible in same class only
II System.out.println("pri_a = " + co.pri_a);
II accessible in same class, subclass of same or other package
II System.out.println("pro_a = " + co.pro_a);
System.out.println("pub_a = " + co.pub_a);
}
}
package pckg2;
public class DemoPackage2 {
public static void main(String ar[]) {
PCKG2_ClassOne obl = new PCKG2_ClassOne();
PCKG2_ClassInOtherPackage ob2 = new PCKG2_ClassInOtherPackage();
}
}
The above file DemoPackage2 belongs to package pckg2, and having an instance of all
classes of pckg2 .
(or)
4. a. Explain How Method Overriding can be prevented in Java? Explain with
a suitable example. 7M
Ans.:
Every Java programmer knows that final modifier can be used to prevent method overriding
in Java because there is no way someone can override final methods; but, apart from final
modifier,
16
Best Way to Prevent Method Overriding in Java
As far as Java best practice is concern, you should always use final keyword to indicate that
a method is not meant for overriding. final modifier has a readability advantage, as well as
consistency advantage, because as soon as a Java programmer sees a final method, he
knows that this can not be overridden. Private method implies that this method is only
accessible in this class, which in turns implies that, you can not override private methods on
derived class. As you can see, private methods still requires one more step to realize that it
can not be overridden. What creates confusion with private and static methods are that, you
can hide these methods in subclass. There is a difference between method hiding and
method overriding, A method is hidden in subclass, if it signature is same as of super class
method, but at a call to hidden method is resolved during compile time, while a call to
overridden method is resolved during run time.
System.out.println(b.name());
class Base
where();
return "Base";
17
private void where()
4.b. Write a java program to implement package and sub package concept. 7M
Ans.:
Creating package :
package pack;
public class A
{
public void msg(){System.out.println("Hello");
}
}
Importing package:
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
package com.ece.core;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello subpackage");
}
}
UNIT-III
18
5. a. Explain any two Exceptions with a suitable example. 7M
Ans.:
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2
completed");}
catch(Exception e){System.out.println("common task completed");}
5. b. Write a Java program to create a user defined thread using Thread class.
7M
Ans.:
How to create thread
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Thread()
Thread(String name)
Thread(Runnable r)
public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
19
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
System.out.println("thread is running...");
t1.start();
(or)
6. a. Write a Java program to create own exceptions using Exception class. 8M
Ans.:
Java own Exception:
If you are creating your own Exception that is known as custom exception or user-
defined exception. Java custom exceptions are used to customize the exception
according to user need.
By the help of custom exception, you can have your own exception and message.
class TestCustomException1{
20
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
21
public final void notifyAll()
UNIT-IV
22
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
23
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
7. b. Explain architecture and execution of an Applet with suitable example.
7M
Ans.:
With the Java Plug-in, applets are not run in the JVM inside the browser. Instead, they are
executed in a separate process. ... An applet can also request to be executed in the
separate JVM. The browser and the applet can still communicate with one another, however.
Architecture
24
A Java applet runs in the context of a browser. The Java Plug-in software in the browser
controls the launch and execution of Java applets. The browser also has a JavaScript
interpreter, which runs the JavaScript code on a web page.
Code:
</applet>
2. Using an applet viewer. Applet viewer executes your applet in a window. This is fastest
and easiest way to test your applet.
25
In this make a separate file AppletHtml.html of same code as above.
Code:
</applet>
C:\>appletviewer AppletHtml.html
3. Better is one more way which is more commonly use - Simply include a comment at the
head of you Java file/program
Code:
/*
</applet>
*/
myapplet.html
<html>
<body>
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
26
import java.awt.Graphics;
g.drawString("welcome to applet",150,150);
/*
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
(or)
8.a. Define AWT Control Button Class.Explain how Buttons are handled in
Applets using Java Applet program? 8M
Ans.: Button is a control component that has a label and generates an event when
pressed. When a button is pressed and released, AWT sends an instance of
ActionEvent to the button, by calling processEvent on the button.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
27
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
28
txtPasswd.setEchoChar('*');
btnHard = new Button("Hardware") ;
btnSoft = new Button("Software") ;
chkC = new Checkbox("C");
chkCpp = new Checkbox("C++");
chkJava = new Checkbox("Java");
cbgCompany = new CheckboxGroup();
optTcs = new Checkbox("Tata Consultancy Services",
cbgCompany, true);
optInfosys = new Checkbox("Infosys", cbgCompany,
false);
optSyntel = new Checkbox("Syntel India Ltd",
cbgCompany, false);
horzCurrent = new Scrollbar(Scrollbar.VERTICAL, 0,1, 1, 101);
vertExpected = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 1, 101);
chCity = new Choice();
chCity.add("Chennai");
chCity.add("Bangalore");
chCity.add("Hyderabad");
chCity.add("Trivandrum");
lstAccompany = new List(4, true);
lstAccompany.add("Father");
lstAccompany.add("Mother");
lstAccompany.add("Brother");
lstAccompany.add("Sister");
add(lblName);
add(txtName);
add(lblPasswd);
add(txtPasswd);
add(lblField);
add(btnHard);
add(btnSoft);
add(lblSkill);
add(chkC);
add(chkCpp);
add(chkJava);
add(lblDreamComp);
add(optTcs);
add(optInfosys);
add(optSyntel);
add(lblCurrent);
add(horzCurrent);
add(lblExpected);
add(vertExpected);
add(txtaComments);
add(lblCity);
add(chCity);
add(lblAccompany);
add(lstAccompany);
btnHard.addActionListener(this);
29
btnSoft.addActionListener(this);
chkC.addItemListener(this);
chkCpp.addItemListener(this);
chkJava.addItemListener(this);
optTcs.addItemListener(this);
optInfosys.addItemListener(this);
optSyntel.addItemListener(this);
horzCurrent.addAdjustmentListener(this);
vertExpected.addAdjustmentListener(this);
chCity.addItemListener(this);
lstAccompany.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Hardware"))
{
btnMsg = "Hardware";
}
else if(str.equals("Software"))
{
btnMsg = "Software";
}
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
g.drawString("Detailed Profile :-", 10, 300);
g.drawString("Field of Interest : " + btnMsg, 10,320);
g.drawString("Software Skill(s) : " , 10, 340);
g.drawString("C : " + chkC.getState(), 10, 360);
g.drawString("C++ : " + chkCpp.getState(), 10, 380);
g.drawString("Java : " + chkJava.getState(), 10,400);
g.drawString("Dream Company : " +
cbgCompany.getSelectedCheckbox().getLabel(), 10,420);
g.drawString("Current % : " +
horzCurrent.getValue(), 10, 440);
g.drawString("Expected % : " +vertExpected.getValue(), 10, 460);
g.drawString("Name: " + txtName.getText(), 10, 480);
g.drawString("Password: " + txtPasswd.getText(), 10,
500);
g.drawString("Preferred City : " +chCity.getSelectedItem(), 10, 520);
30
int idx[];
idx = lstAccompany.getSelectedIndexes();
lstMsg = "Accompanying Persons : ";
for(int i=0; i<idx.length; i++)
lstMsg += lstAccompany.getItem(idx[i]) + " ";
g.drawString(lstMsg, 10, 540);
}
}
31