0% found this document useful (0 votes)
3 views60 pages

java notes

The document contains a compilation of Java programming questions and answers, covering topics such as JIT vs JVM, garbage collection, access modifiers, inheritance, polymorphism, and exception handling. It also includes Java code examples for various concepts like matrix multiplication and binary search. Additionally, it discusses the differences between overloading and overriding, as well as single-threading and multithreading.

Uploaded by

Mahnoor shoukat
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)
3 views60 pages

java notes

The document contains a compilation of Java programming questions and answers, covering topics such as JIT vs JVM, garbage collection, access modifiers, inheritance, polymorphism, and exception handling. It also includes Java code examples for various concepts like matrix multiplication and binary search. Additionally, it discusses the differences between overloading and overriding, as well as single-threading and multithreading.

Uploaded by

Mahnoor shoukat
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/ 60

JAVA

SOLVED
PAST PAPERS

Java is designed by JAMES GOSLING

1
JULY 2016- Java
Question No 1(a)

Q) what is difference between JITand JVM?

Answer:

Just-In-Time Java-virtual-machine
 A JIT is a code generator that  A Java virtual machine (JVM) is a
converts Java bytecode into native virtual machine that enables a
machine code. computer to run Java programs as well
as programs written in other languages
and compiled to Java bytecode
 objective of JIT is to improve  main goal of JVM is to provide
performance of JVM, by compiling platform independence
more code into machine language.
 JIT actually get invented to improve  JVM is older concept than JIT.
performance of JVM.

Q(b): What is the purpose of garbage collection in Java, and when is it used?
ANS: USE OF GARBAGE COLLECTION IN JAVA.
Every time you create an Object memory is allocated from your computers f to store that object.
If you never got rid of these objects then your program would use more and more memory as the
more it allocated objects.

Java therefore contains a garbage collector. This is an automatic memory management system
that detects when objects are no longer necessary and removes them. It does this by checking if
there is anyway the programmer could get a reference to that object. If there are no accessible
references to the object left the garbage collector marks the object as trash and deallocates it at
the next opportunity.

2
Q(c): Q:State the significance of public, private, protected, default modifiers
both singly and in combination and state the effect of package relationships on
declared items qualified by these modifiers.
Answer:

Public:Public class is visible in other packages, field is visible everywhere (class must be
public too)

Private: Private variables or methods may be used only by an instance of the same class that
declares the variable or method, A private feature may only be accessed by the class that owns
the feature.

Protected:Is available to all classes in the same package and also available to all subclasses
of the class that owns the protected feature.

This access is provided even to subclasses that reside in a different package from the class that
owns the protected feature. What you get by default i.e., without any access modifier (ie, public
private or protected). It means that it is visible to all within a particular package.

QUESTION NO 2:
Question: Class object
I. Department of computer science University of Department of computer science.
and university of Karachi. Karachi.
II. Mickey Mouse and rodent. Rodent. Mickey Mouse.

III. Author and WilliamShakespeare. Author. William Shakespear.

IV. Sports and football. Sports. Football.

2(b) DEFINE.

 Inheritance in Java:is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system). The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes.
 Polymorphism:is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object. In Java, all Java objects are polymorphic since any object will pass the IS-A test for
their own type and for the class Object.
 Java Superclass:is a class which gives a method or methods to a Java subclass. A Java class
may be either a subclass, a superclass, both, or neither! The Cat class in the following example is
the subclass and the Animal class is the superclass.

3
 Java subclass: is a class which inherits a method or methods from a Java superclass. A Java
class may be either a subclass, a superclass, both, or neither! The Cat class in the following
example is the subclass and the Animal class is the superclass.
 Abstract class:Abstraction is a process of hiding the implementation details and showing only functionality
to the user. A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

2(c) what are the two ways to create polymorphism in a programming language?

Ans: Java supports 2 types of polymorphism:

Static or compile-time.

In Java, static polymorphism is achieved through method overloading. Method overloading


means there are several methods present in a class having the same name but different
types/order/number of parameters.

At compile time, Java knows which method to invoke by checking the method signatures. So,
this is called compile time polymorphism or static binding

Dynamic:

Dynamic Method Dispatch or Runtime Polymorphism in Java. Method overriding is one of the
ways in which JavasupportsRuntime Polymorphism. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved at run time, rather than compile
time. ... Thus, this determination is made at run time.

QUESTION NO 3:

3(a): ANS: The java Statement that creates the subclass by inheritance is

Class MorefunClass extends FunClass{}

Show,tell,smile: these methods are inherited and accessible fromFunClass because


MorefunClass extends FunClass, and because these are in public FunClass.
MorefunClass also includes all the methods of java.lang.object because all classes
extends object.

3(b): ANS:
importjava.util.Scanner;

publicclassPostive_Negative

4
{

publicstaticvoidmain (String [] args)

int n;

Scanner s =newScanner(System.in);

System.out.print("Enter the number you want to check:");

n =s.nextInt();

if(n >0)

{ System.out.println("The given number "+n+" is Positive");

elseif(n <0)

System.out.println("The given number "+n+" is Negative");

else

{ System.out.println("The given number "+n+" is Zero ");} } }

3(c): Write a Java expression which represents the floating-point constant

two thirds.

Solution:

2./3 or (double)2/3 Or 2.0/3.0

3(d):If x and y are Java variables of type double, write the Java code for

the mathematical expression

x2+ 2/ 3y-5

Solution:

(Math.pow(x,2) + 2) / (3*y - 5).

5
QUESTION NO 4:
(a) ANS:

If we have a try block and have three statements, if an exception occurred in statment2 then it is obvious
that the statment3 will not be executed because it cannot throw two exceptions together. Hence the
statment3 will be left executing.

(b) what is the difference between multitasking and multithreading?

Multithreading Multitasking
It supports execution of multiple parts of a It supports execution of multiple programs
single program simultaneously. simultaneously
All threads share common address space Each process has its own address space.
Context switching is low cost. Context switching is high cost.
Interthread communication is inexpensive. Interprocesscommunication is expensive.
Thread is light weight task. Process is heavy weight task.
It is under the control of java. It is not in under control of java.

QUESTION NO 4:

(c) what are different types of states for a thread in java?

A thread lies only in one of the shown states at any instant:

1. New Thread: When a new thread is created, it is in the new state. The thread has not yet started
to run when thread is in this state.
2. Runnable State: A thread that is ready to run is moved to runnable state. In this state, a thread
might actually be running or it might be ready run at any instant of time.
3. Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the following
states:
 Blocked
 Waiting
4. Timed Waiting: A thread lies in timed waiting state when it calls a method with a time out
parameter.
5. Terminated State: A thread terminates because of either of the following reasons:
 Because it exists normally. This happens when the code of thread has entirely executed by the
program.
 Because there occurred some unusual erroneous event, like segmentation fault or an unhandled
exception.

(d)write a java program to find duplicate characters in a string.

public class DuplStr {

public static void main (String argu[])

{ String str = "w3schools";

6
int cnt = 0;

char[] inp = str.toCharArray();

System.out.println("Duplicate Characters are:");

for (int i = 0; i<str.length(); i++)

for (int j = i + 1; j <str.length(); j++)

if (inp[i] == inp[j]) { System.out.println(inp[j]); cnt++; break; } } } } }

7
COMPUTER SCIENCE JAVA:-25-june-2014:-

Question#1;

A. INHERITANCE:

Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).The idea behind inheritance in Java is that you can create new
classes that are built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
B. INTERFACE:

An interface in Java is similar to a class, but the body of an interface can include only abstract
methods and final fields (constants). A class implements an interface by providing code for each
method declared by the interface. Here’s a basic interface that defines a single method,
named Playable, that includes a single method named play:
C. public interface Playable
D. {
E. void play();
F. }

This interface declares that any class that implements the Playable interface must provide an
implementation for a method named play that accepts no parameters and doesn’t return a value.
C. AGGREGATION:
Aggregation in Java is a relationship between two classes that is best described as
a "has-a" and "whole/part" relationship. It is a more specialized version of the association
relationship. The aggregate class contains a reference to another class and is said to have ownership of
that class. Each class referenced is considered to be part-of the aggregate class.

For example, if you imagine that a Student class that stores information about individual students at a
school. Now assume a Subject class that holds the details about a particular subject (e.g., history,
geography). If the Student class is defined to contain a Subject object then it can be said that the Student
object has-a Subject object. The Subject object also makes up part-of the Student object -- after all, there
is no student without a subject to study. The Student object, therefore, owns the Subject object.

D. OPERATOR OVERLOADING:

Operator overloading is a technique by which operators used in a programming language are


implemented in user-defined types with customized logic that is based on the types of arguments passed.
Operator overloading facilitates the specification of user-defined implementation for operations wherein
one or both operands are of user-defined class or structure type. This helps user-defined types to behave
much like the fundamental primitive data types. Operator overloading is helpful in cases where the
operators used for certain types provide semantics related to the domain context and syntactic support as
found in the programming language. It is used for syntactical convenience, readability and
maintainability.
Java does not support operator overloading, except for string concatenation.

8
E. EXCEPTION HANDLING:

The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained. In Java, an
exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

Question#2;

DIFFERENCE BETWEEN:-

OVERLOADING OVERRIDING
Overloading happens at compile- Overriding happens at runtime:
time
Static methods can be overloaded Static methods cannot be overridden,
which means a class can have even if you declare a same static
more than one static method of method in child class it has nothing to
same name do with the same method of parent
class.
Argument list should be different Argument list should be same in
while doing method overloading. method Overriding.

ABSTRACT CLASSES INTERFACE CLASSES


An abstract class can extend only An interface can extend any number of
one class or one abstract class at a interfaces at a time
time
An abstract class can have An interface can have only have public
protected and public abstract abstract methods
methods
In abstract class keyword “abstract” In an interface keyword “abstract” is
is mandatory to declare a method optional to declare a method as an
as an abstract abstract

SINGLE THREAD MULTITHREADING


Single threading is the processing Multithreading is a widespread
of one command at a time programming and execution model
that allows multiple threads to exist
Within the context of one process.
In the formal analysis of the Multithreading can also be applied to
variables semantics and process one process to enable parallel
state the term single threading execution on a multiprocessing system
It can be used differently to mean Multithreading is allowing process to
backtracking within a single thread create more threads which increase
the responsiveness of the system

9
Question#3;

A. MATRIX MULTIPLICATION CODE:

package matrix;

import java.util.Scanner;

public class Matrix {

public static void main(String args[]){

int n;

Scanner input = new Scanner(System.in);

System.out.println("Enter the base of squared matrices");


n = input.nextInt();

int[][] a = new int[n][n];

int[][] b = new int[n][n];

int[][] c = new int[n][n];


System.out.println("Enter the elements of 1st martix row wise \n");

for (int i = 0; i < n; i++)


{

for (int j = 0; j < n; j++)


{

a[i][j] = input.nextInt();

}
}

System.out.println("Enter the elements of 2nd martix row wise \n");


for (int i = 0; i < n; i++)

{
for (int j = 0; j < n; j++)

10
b[i][j] = input.nextInt();
}

}
System.out.println("Multiplying the matrices...");

for (int i = 0; i < n; i++)

{
for (int j = 0; j < n; j++)

for (int k = 0; k < n; k++)


{

c[i][j] = c[i][j] + a[i][k] * b[k][j];

}
}

System.out.println("The product is:");


for (int i = 0; i < n; i++)

for (int j = 0; j < n; j++)

System.out.print(c[i][j] + " ");


}

System.out.println();

input.close();

B. BINARY SEARCH PROGRAM:


package binarysearch;

import java.util.Scanner;

11
class Binarysearch {

public static void main(String args[])

int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

first = 0;

last = n - 1;

middle = (first + last)/2;

while( first <= last )

if ( array[middle] < search )

first = middle + 1;

else if ( array[middle] == search {

System.out.println(search + " found at location " + (middle + 1) + ".");

break;

else

last = middle - 1;

middle = (first + last)/2; }

12
if (first > last) System.out.println(search + " isn't present in the list.\n");

}}

C.USING STACK FUNCTION TO DISPLAY INPUT IN REVERSE ORDER:


1. class Program
2. {
3. static void Main(string[] args)
4. {
5. Stack<string> stack = new Stack<string>();
6. stack.Push("a");
7. stack.Push("b");
8. stack.Push("c");
9. stack.Push("d");
10. stack.Push("e");
11. stack.Push("f");
12.
13. ReverseStack(stack);
14. }
15.
16. private static void ReverseStack<T>(Stack<T> stack)
17. {
18. for (int i = 0; i < stack.Count; i++)
19. {
20. T targetElement = stack.Pop();
21. ReverseStackStep(stack, stack.Count - i, 0,
targetElement);
22. }
23. }
24.
25. private static void ReverseStackStep<T>(Stack<T> stack, int
limit, int currentLevel, T targetElement)
26. {
27. if (currentLevel == limit)
28. {
29. stack.Push(targetElement);
30. }
31. else
32. {
33. T element = stack.Pop();
34. ReverseStackStep(stack, limit, currentLevel + 1,
targetElement);
35. stack.Push(element);
36. }
37. }
38. }
Question#5;

Write a complete java program to display 1to100 numbers.your program should invoke separate threads

to display even and odd numbers.

package mythreads;

13
public class Mythreads

public static void main(String[] args) {

Runnable r = new Runnable1();

Thread t = new Thread(r);

t.start();

Runnable r2 = new Runnable2();

Thread t2 = new Thread(r2);

t2.start();

class Runnable2 implements Runnable{

public void run(){

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

if(i%2 == 1)

System.out.println(i);

}class Runnable1 implements Runnable{

public void run(){

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

if(i%2 == 0)

System.out.println(i);

}}

14
JAVA(26 December 2011)
Question no: 1

What is the difference between an interface and an abstract class? Explain the difference
with coding.

Abstract class vs Interface


Abstract class Interface

It can have default method implementation Interfaces are pure abstraction.It can not have
implementation at all.

Subclasses use extends keyword to extend an subclasses use implements keyword to implement
abstract class and they need to provide interfaces and should provide implementation for
implementation of all the declared methods in the all the methods declared in the interface
abstract class unless the subclass is also an
abstract class

Abstract class can have constructor Interface can not have constructor

Abstract classes are almost same as java classes Interfaces are altogether different type
except you can not instantiate it.

Abstract class methods can have public Interface methods are by default public. you can
,protected,private and default modifier not use any other access modifier with it

Abstract classes can have main method so we can Interface do not have main method so we can not
run it run it.
Abstract class can extends one other class and can Interface can extends to one or more interfaces
implement one or more interface. only

It is faster than interface Interface is somewhat slower as it takes some time


to find implemented method in class

If you add new method to abstract class, you can provide default If you add new method to interface, you have to change the
implementation of it. So you don’t need to change your current classes which are implementing that interface
code

15
Example: Example:
0 public class Employee implements Externalizabl 0 public class HttpServlet extends GenericServl
1 e{ 1 et
02 02 {
03 int employeeId; void service(ServletRequest req,
03
ServletResponse res)
04 String employeeName;
04 {
05
05 // implementation
06
06 }
07 @Override
07 protected void doGet(HttpServletRequest
public void readExternal(ObjectInput
08 req, HttpServletResponse resp)
in) throws IOException,
08 {
ClassNotFoundException
09 09 // Implementation
{ employeeId=in.readInt();
10 employeeName=(String) in.readObject(); 10 }
11 11
12 } @Override 12 protected void doPost(HttpServletRequest
req, HttpServletResponse resp)
public void writeExternal(ObjectOutput
13 13 {
out) throws IOException {
14 14 // Implementation

15 out.writeInt(employeeId); 15 }

16 out.writeObject(employeeName); } 16

17 } // some other methods related to


17
HttpServlet
18 }

Question no: 2

Describe synchronization in respect to multithreading ?Explain with suitable example.

Multithreading with Synchronization:


When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issues. For example, if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be closing
the same file.

So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a thread
can lock or unlock. Only one thread at a time may hold a lock on a monitor.Java
programming language provides a very handy way of creating threads and synchronizing
their task by using synchronized blocks. You keep shared resources within this block.
Following is the general form of the synchronized statement

16
Multithreading Example with Synchronization:
Here is the same example which prints counter value in sequence and every time we run it,
it produces the same result.

Example

class PrintDemo { public void start () {

public void printCount() { System.out.println("Starting " +


threadName );
try {
if (t == null) {
for(int i = 5; i > 0; i--) {
t = new Thread (this, threadName);
System.out.println("Counter ---
" + i ); } t.start ();

} catch (Exception e) { }}}

System.out.println("Thread public class TestThread {


interrupted.");
public static void main(String args[]) {
}}}
PrintDemo PD = new PrintDemo();
class ThreadDemo extends Thread {
ThreadDemo T1 = new ThreadDemo( "Thread
private Thread t; - 1 ", PD );

private String threadName; ThreadDemo T2 = new ThreadDemo( "Thread


- 2 ", PD );
PrintDemo PD;
T1.start();
ThreadDemo( String name, PrintDemo pd) {
T2.start();
threadName = name;
// wait for threads to end
PD = pd;
try {
}
T1.join();
public void run() {
synchronized(PD) { T2.join();

PD.printCount(); } catch ( Exception e) {

} System.out.println("Interrupted");

System.out.println("Thread " + }}}


threadName + " exiting.");

17
Question no: 3

How do I serialize an object to a file give an example to save and restore the object after
application restart?

Java Program to Serialize an Object using Serializable interface


Here is our Java program to demonstrate how to serialize and de-serialize an object in Java.
This program contains two classes Shoe and SerializationDemo, the first class is our
POJO, we will create object of this class and serialieze it. The second class is our application
class which contains the main() method, all the code to create object, saving it, and finally
restoring it written inside main method.
import java.io.File; class Shoe implements Serializable {
import java.io.FileInputStream;
import java.io.FileOutputStream; // static final variable
import java.io.IOException; private static final long
import java.io.ObjectInputStream; serialVersionUID = 40L;
import java.io.ObjectOutputStream; private static final Logger logger =
import java.io.Serializable; Logger.getLogger(Shoe.class.getName());
import java.util.logging.Logger;
// static variable but not final
/** private static String _brand;
* Simple example of Serialization in
Java. We first create a Shoe object, then // instance variable
* serializes it and finally restored it private int _id;
by using de-serialization. private int _size;
* private String _color;
* @author Javin Paul
*/ // transient variable
public class Pattern { private transient boolean
_isRunningShoe;
public static void main(String
args[]) throws IOException, // non serializable field
ClassNotFoundException { Thread _thread;
Shoe whiteNikeShoe = new
Shoe("Nike", 1000, 9, "WHITE", true); public Shoe(String brand, int id, int
System.out.println("Before size, String color, boolean
Serialization"); isRunningShoe) {

18
whiteNikeShoe.print(); System.out.println("Inside
Constructor");
// serializing shoe object _brand = brand;
writeShoe(whiteNikeShoe); _id = id;
_size = size;
// creating another Shoe with _color = color;
different brand _isRunningShoe = isRunningShoe;
Shoe blackAdidasShoe = new
Shoe("Adidas", 2000, 8, "Black", true); }

public String brand() {


// deserializing shoe object return _brand;
whiteNikeShoe = (Shoe) }
readShoe();
public int id() {
System.out.println("After return _id;
DeSerialization"); }
whiteNikeShoe.print();
} public int size() {
return _size;
private static void }
writeShoe(Serializable shoe) throws
IOException { public String color() {
ObjectOutputStream oos = new return _color;
ObjectOutputStream(new }
FileOutputStream(new File("shoe.ser")));
oos.writeObject(shoe); public void print() {
oos.close();
} System.out.println("SerialVersionUID
(final static field) : " +
private static Object readShoe() serialVersionUID);
throws IOException, System.out.println("logger
ClassNotFoundException { ((final static field) : " + logger);
ObjectInputStream ois = new System.out.println("_brand
ObjectInputStream(new FileInputStream(new (static field) : " + _brand);

19
File("shoe.ser"))); System.out.println("_id (instance
Object obj = ois.readObject(); variable) : " + _id);
return obj; System.out.println("_size
} (instance variable) : " + _size);
System.out.println("_color
} (instance variable) : " + _color);

System.out.println("_isRunningShoed
(transient variable) : " +
_isRunningShoe);
System.out.println("_thread (non-
serializable field) : " + _thread);

20
Question no: 4

Can a top level class can be private or protected ?Discuss with suitable examples.

No, a sub level class as private would be completely useless because nothing would have
access to it. If a top level class is declared as private the compiler will complain that the
“modifier private is not allowed here”. This means that the top level class cannot be private.
Private classes are allowed but only as inner or nested classes. If you have a private inner or
nested class, then access is restricted to the scope of the outer class.

Protected class member is just like package- private except that it also can be accessed from subclasses.
Defining a field protected makes that field accessible inside the package as well as outside the package
through inheritance only (Only inside the subclass). If all the classes are allowed to subclass then it will be
similar to public access specifier. Since there is no way to restrict this class being subclasses by only few
classes, there is no use of protected access specifiers for top level classes. Hence it is not allowed.

Question no: 5

Does importing a package imports the subpackages as well? Example does important
com.mytest.* also imports com.mytest.unitest.

ANSWER:

There is no such thing as sub-package in java.

Java.util.stream is not a sub package of java.util.


Therefore import java.util.* doesn’t import the classes of java.util.stream.
To import all the built in classes, you have to import them one package at a time. It’s a better
practice, though, to only import the classes that you actually need.

21
Question no: 6

a) Can I import same package class twice will the JVM load the package twice at
runtime?

Yes, we can import same package/class multiple times. It will not create any problem .
Neither compiler nor JVM will complain about it.

JVM will internally load the class only once no matter how many times you
import the same class.

b) What is the garbage collector and how it works?

Garbage collection:
Garbage means unreferenced objects. Garbage Collection is a way to destroy the unused
objects. In java it is performed automatically. So, java provides better memory
management.

Question no: 7

If I do not provide any argument on the command line then the string array of main
method will be empty or null? Provide a suitable example where input arguments are
used.

When you do not pass anything, the args is not null - it is empty:
if(args.length == 0)
{
System.out.println("I am empty");
} else{
System.out.println(args);
}

22
Question no: 8

a) What if the main method is declared as private?

Yes, we can declare main method as private. It compiles without any errors, but in
runtime, it says main method is not public.

b) How JVM works?

JVM initializes, lays out the memory for different purposes and first puts all the
machine/native implementations of each bytecode linearly or in contiguous way with a
hash like logic allowing address resolution of next bytecode code in the memory. Each
bytecode has an entry point(prologue), actual execution logic(native routine which
represents the byte code and hence it is interrupted) for the bytecode and exit
point(epilogue).

Question no: 9

State the significance of public private protected default modifiers both singly and in
combination and state the effect of package relationships on the declared items qualified
by these modifiers?

ANSWER: PG # 3

23
Question no: 10

Difference between Swing and AWT

Difference between AWT and Swing in java


AWT Swing

Swing is a part of Java Foundation Class


AWT stands for Abstract Window Toolkit. (JFC).

AWT components are heavy weight. Swing components are light weight.
AWT components are platform dependent Swing components are platform
so there look and feel changes according to independent so there look and feel remains
OS. constant.
AWT components are not very good in look
and feel as compared to Swing Swing components are better in look and
components. See the button in below feel as compared to AWT. See the button in
image, its look is not good as button below image, its look is better than button
created using Swing. created using AWT.

24
14-jan-2013:
Qno:1 :- Provide suitable coding Example along with brief description :

Encapsulation:

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will
be hidden from other classes, and can be accessed only through the methods of their
current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the variables values.

package encapsulate;
public class Encapsulate {
/** * @param args the command line arguments
*/
public static void main(String[] args) {
Emp e1 = new Emp();
e1.setEmpId(563);
e1.setEmpName("Tazeen");
Emp e2 = new Emp();
e2.setEmpId(564);
e2.setEmpName("Zafar");
System.out.println("Employe Name: "+e1.getEmpName());
System.out.println( "Emp Id: "+e1.getEmpId());
System.out.println("Emp Name: "+e2.getEmpName());
System.out.println( "Emp Id : "+e2.getEmpId());
}
}
class Emp {

private int empId;

public int getEmpId() {


return empId;
}

25
public void setEmpId(int empId) {
this.empId = empId;
}

public void setEmpName(String empName) {


this.empName = empName;
}

public String getEmpName() {


return empName;
}
private String empName;
}

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).
package inherit;

import java.util.Scanner;

/**
*
* @author IBA iTech
*/
public class Inherit {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
AddSubobj = new AddSub();
obj.num1=9;
obj.num2=2;
obj.sum();
System.out.println(obj.result);
obj.sub();

26
System.out.println(obj.result);
}
}
class Add
{
int num1,num2,result;
public void sum()
{
result= num1+num2;
}
}
class AddSub extends Add
{
public void sub()
{
result= num1-num2;
}
}

FUNCTION OVERLOADING:
An overloaded function is really just a set of different functions that happen to have the same
name. The determination of which function to use for a particular call is resolved at compile
time. In the Java programming language, function overloading is also known as compile-time
polymorphism and static polymorphism. Overloaded functions enable programmers to supply
different semantics for a function, depending on the types and number of arguments.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package fun_overload;
/**
*
* @author IBA iTech
*/
public class Fun_Overload {
int add(int a,int b)
{
return a+b; }
String add(String s1,String s2) {
return s1+s2; }
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Fun_Overloadfov=new Fun_Overload();
System.out.println("Code For Function Overloading ");

27
System.out.println(fov.add(6,4));
System.out.println(fov.add("tazeen","zafar"));} }

ABSTRACT CLASSES:
Java Abstract class can implement interfaces without even providing the implementation of
interface methods. Java Abstract class is used to provide common method implementation to all
the subclasses or to provide default implementation. We can run abstract class in java like any
other class if it has main() method.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.*/
package javaapplication25;
/**
*
* @author IBA iTech
*/
abstract class Abs_class {
abstract void fun(); }
class Derived extends Abs_class {
void fun() {
System.out.println("Hello Class Derived here");
}}
class Main {
public static void main(String args[]) {
// Uncommenting the following line will cause compiler error as the
// line tries to create an instance of abstract class.
// Base b = new Base();
// We can have references of Base type.
Abs_class b = new Derived();
b.fun(); }}

Qno:2 Write a complete JAVA prograom of the following specification. (10 marks)

1. To Display even N numbers.


0,2,4,6,8,10.........N

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication23;
import java.util.*;
/**
*
* @author IBA iTech
*/
public class N Even NUMBERS {

28
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

int n=0,i=0;

Scanner X = new Scanner(System.in);

System.out.print("Enter value n : ");


n = X.nextInt();

for(i=1; i<n; i++)


{
if(i%2==0)
System.out.print(i+" ");
}
System.out.println();

}
}

2. To display following patterns on screen not by direct printing for any given
value of N. For N=5
1
12
123
1234
12345
*/
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package num_pattern;

/**
*
* @author IBA iTech
*/
public class Num_pattern {

/**
* @param args the command line arguments
*/

29
public static void main(String[] args) {
// TODO code application logic here
int rows = 5;

for(int i = 1; i<= rows; ++i) {


for(int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}

}
}

Ques:no3 : write any two programs (8 marks ,4 marks to each)

 write a complete java program to show your skills for data base
connnectivity. You are required to store your BCS Examination
record.
 Write a complete java to show your skills in socket programming
. You may provide a program to peer to peer chatting client.
 Explain working of java libraries for GUI with examples of
SWING and AWT (you may use example for data editing form)

30
JAVA DEC 2014
Q25:Explain similarities and differences and when you would use one rather than
the other

JApplet and Simple JAVA Aplication


Similarities:

Japplet Java Applications


Java Applets arecompiled using Java applications are compiled using
the javac command the javac command

27: Define a java class of your own to represent a linked list provides it with
methods that can be used to reverse a list and append two lists. Comment
whether your design has led you to make the methods for reverse and append.

Ans: // Java program for reversing the linked list

classLinkedList {

staticNode head;

staticclassNode {

intdata;
Node next;
Node(intd) {
data = d;
next = null;
}
}

/* Function to reverse the linked list */


Node reverse(Node node) {
Node prev = null;

31
Node current = node;
Node next = null;
while(current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
returnnode;
}

// prints content of double linked list


voidprintList(Node node) {
while(node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}

publicstaticvoidmain(String[] args) {
LinkedList list = newLinkedList();
list.head = newNode(85);
list.head.next = newNode(15);
list.head.next.next = newNode(4);
list.head.next.next.next = newNode(20);

System.out.println("Given Linked list");


list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}

Above methods is designed to reverse a linked list of integers


32
Q27(a): Define the term Byte code-

Ans: Byte code:-

Byte code is object-oriented programming (OOP) code compiled to run on a virtual


machine (VM) instead of a central processing unit (CPU). The VM transforms
program code into readable machine language for the CPU because platforms
utilize different code interpretation techniques. A VM converts byte code for
platform interoperability, but byte code is not platform-specific.
Byte code is in a compiled Java programming language format and has the .class
extension executed by Java Virtual Machine (JVM).
This term is also known as portable code (p-code) and intermediate code.
Example: considering the java code:
outer:
for (int i = 2; i < 1000; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
continue outer; }

System.out.println (i);
}

(b): What do you understand by type conversion?

Ans: Type Conversion:-

When you assign value of one data type to another, the two types might not be
compatible with each other. If the data types are compatible, then Java will
perform the conversion automatically known as Automatic Type Conversion and if
not then they need to be casted or converted explicitly. For example, assigning an
int value to a long variable

Example:

// Demonstrate casts.
class Conversion {
public static void main(String args[]) {

33
byte b;

int i = 257;

double d = 323.142;

System.out.println("\nConversion of int to byte.");

b = (byte) i;

System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int.");

i = (int) d;

System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte.");

b = (byte) d;

System.out.println("d and b " + d + " " + b);

This program generates the following output:

Conversion of int to byte.

i and b 257 1

Conversion of double to int.

d and i 323.142 323

Conversion of double to byte.

d and b 323.142 67

34
(c): Name two JUMP statements in java and their use

Ans: Java supports three jump statements: break, continue, and return. These
statements transfer control to another part of the program.

Break:
Using break In Java, the break statement has three uses. First, as you have seen, it
terminates a statement sequence in a switch statement. Second, it can be used to
exit a loop. Third, it can be used as a “civilized” form of goto.

Example:

/* Print 1 to 10 using Break Statement Java Example*/


classBreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10) break;
System.out.print(i+" ");
i++;}}}
Continue :
This command skips the whole body of the loop and executes the loop with the next iteration.
On finding continue command, control leaves the rest of the statements in the loop and goes
back to the top of the loop to execute it with the next iteration (value).
/* Print Number from 1 to 10 Except 5 */
classNumberExcept
{

35
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5) continue;
System.out.print(i +" ");
}
}
}

(d) What is exception? Name two Exception handling Blocks-


Ans: Exception:
Exceptions are events that occur during the execution of programs that disrupt the normal flow of
instructions (e.g. divide by zero, array access out of bound, etc.).When an exceptional condition arises,
an object representing that exception is created and thrown in the method that caused the error
The two Exception Handling blocks are: Try and Catch
Example:
This is the general form of an exception-handling block:

try {

// block of code to monitor for errors

catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

catch (ExceptionType2 exOb) {

36
// exception handler for ExceptionType2

// ...

finally {

// block of code to be executed before try block ends

(d) Write two advantages of using functions in program

Advantages Of Functions:

1- A function can be used to keep away from rewriting the same block of codes which we
aregoing use two or more locations in a program.This is especially useful if the code
involved islong or complicated.
2- The length of the source program can be reduced by using functions at appropriate
places
For Example:

 print() is a method of java.io.PrintSteam. The print("...") prints the string


inside quotation marks.

37
JUNE 2013:

2. Reference Semantics Mystery

Write the output of the following program below, as it would appear on the console

public class ReferenceMystery {

public static void main(String[] args) {

String name = "Janet";

int money = 30;

Account a = new Account(name, money);

38
mystery(name, money, a);

System.out.println(name + ", " + money + ", " + a);

money = money + 10;

a.name = "Billy";

mystery(name, money, a);

System.out.println(name + ", " + money + ", " + a);

public static void mystery(String name, int money, Account a) {

a.money++;

name = "Susan";

System.out.println(name + ", " + money + ", " + a);

}}

public class Account {

String name;

int money;

public Account(String name, int money) {

this.name = name;

this.money = money;

public String toString() {

return name + ": $" + money;

}}

SOLUTION:
Susan, 30, Janet: $31

Janet, 30, Janet: $31

39
Susan, 40, Billy: $32

Janet, 40, Billy: $32

SOLUTION:
Rose Lily
Tulip 1
Lily 2 Tulip 1

Lily
Violet 1 Lily 1
Lily 2 Violet 1 Lily 1

Violet
Violet 1
Violet 2

40
Rose Lily
Violet 1 Lily 1
Lily 2 Violet 1 Lily 1

4. File Processing
Write a static method named groceries that accepts as its parameter a Scanner for an input file.
The data in the
Scanner represents grocery items purchased along with their price and their discount category.
Your method should
compute and return a double representing the total cost of the grocery items.
Each item is represented by three tokens starting with the name of the item (a single word)
followed by its discount
category ("red", "blue" or "none") followed by its full price. The discount category may include
capitalization. The
different discount options are:
• red: 10% off full price
• blue: 25% off full price
• none: full price
For example, given a Scanner named input referring to an input file that contains the following
text:
avocado RED 1 blueberries none 5 milk blue
2.00 cream red 1.00 cereal None 1.29
The call on groceries(input) should return 9.59.
The avocado will cost $0.9 because a discount of 10% off of $1 is $0.1. Blueberries cost the full
price of $5. Milk
will cost $1.50 because it receives a discount of 25% off of $2.00. Cream will cost $0.9 and
cereal will cost the full
price of $1.29. The total is 0.9 + 5 + 1.5 + .9 + 1.29 = 9.59.
Notice that the input may span multiple lines and may have different spacing between tokens.
The entire file
represents a single grocery bill.
You may assume that the input file exists and has the format described above. The file will
always contain at least
one grocery item and will always contain a number of tokens that is a multiple of 3. The second
token in every triple
will always be one of "red", "blue" or "none".

SOLUTION:
There are two possible solutions for this problem:

// reads price in each branch, 3 counters, calculates discount at end


public static double groceries(Scanner s) {

41
double red = 0;
double blue = 0;
double none = 0;
while (s.hasNext()) {
s.next();
String sale = s.next();
if (sale.equalsIgnoreCase("red")) {
red += s.nextDouble();
} else if (sale.equalsIgnoreCase("blue")) {
blue += s.nextDouble();
} else {
none += s.nextDouble();
}
}
return red * .90 + blue * .75 + none;
}

// reads price once before conditional, adds in each branch


public static double groceries(Scanner s) {
double total = 0;
while (s.hasNext()) {
s.next();
String sale = s.next();
double value = s.nextDouble();
if (sale.equalsIgnoreCase("red")) {
total += value * .90;
} else if (sale.equalsIgnoreCase("blue")) {
total += value * .75;
} else {
total += value;
}
}
return total;
}
5. Array Programming

Write a static method named countCommon that accepts three arrays of strings as parameters
and returns an integer
count of how many indexes store exactly the same string in all three arrays. For example, if the
arrays are:
// index
0
1
2

42
3
4
5
6
7
String[] a1 = {"hi", "Ed", "how", "are", "you", "folks", "DoIng", "today?"};
String[] a2 = {"hi", "Bob", "how", "are", "YOUR", "kids", "doing", "today?"};
String[] a3 = {"hi", "you", "how", "are", "you", "guys", "DOING", "today?"};
Then the call of countCommon(a1, a2, a3) should return 4 because indexes 0, 2, 3, and 7 store
exactly the same
string in all three arrays. Indexes 1, 4, 5, and 6 do not. (Index 6 differs by capitalization.)
The arrays might not be the same length. An index must be within the bounds of all three
arrays to be considered.
For example, given the arrays below, the call of countCommon(a4, a5, a6) should return 3
because all three
arrays store the same values at indexes 0, 2, and 5:
// index
0
1
2
3
4
5
6
7
String[] a4 = {"hi", "Ed", "how", "ARE", "you", "Doing", "I'm", "fine"};
String[] a5 = {"hi", "Bob", "how", "are", "YOU", "Doing"};
String[] a6 = {"hi", "you", "how", "is", "you", "Doing", "this", "fine", "day?"};
For full credit, do not modify the elements of the arrays passed in. Do not make any
assumptions about the length of
the arrays or the length of the strings stored in them. You may assume that none of the arrays
or elements are null.
SOLUTION:
(Here it is shown how to print the common elements from an
array and not the number of common elements as asked in
the question)m
static void countCommon(int[] arr, int[] arr2, int[] arr3)
{
for(int i=0;i<arr.length; i++)
{
int count=0;

43
for (int j=0; j<arr2.length; j++)
{
if(arr[i]==arr2[j])
count++;
}
if(count>=1)
{
for (k=0;k<arr3.length; k++)
{
if(arr[i]==arr3[k])
System.out.println("Common elements are:" +arr3[k]);
}}}
Public static void main(String args[])
{
countCommon(new int[]{2,3,4,5},new int[]{10,7,3,6},new int[]{11,9,3})
}}

SOLUTION:
0.10
Book price before tax: 100.0
Book price after tax: 110.0 Tax paid:
10

44
SOLUTION:
int sum=0;
for (inti=3;i<100;i=i+3)
sum=sum+i;

45
Jan-2016 (Section B)
QUESTION NO. 1:
a) What is a Thread? Describe the complete life cylcle of a thread.
Thread:
Multithreading refers to two or more tasks executing concurrently within a single
program. A thread is an independent path of execution within a program. Many threads
can run concurrently within a program. Every thread in Java is created and controlled by
the java.lang.Thread class. A Java program can have many threads, and these threads
can run concurrently, either asynchronously or synchronously.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

46
1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.

3) Running
The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated
A thread is in terminated or dead state when its run() method exits.

b) Write a program to demonstrate the following

1. to convert lower case string to upper case.


/*Java Program Example - Convert Lowercase String to Uppercase*/

import java.util.Scanner;

public class JavaProgram


{
public static void main(String[] input)
{
String strUpper, strLower;
Scanner scan = new Scanner(System.in);

System.out.print("Enter one word/name in Lowercase : ");


strUpper = scan.nextLine();

strLower = strUpper.toUpperCase();
System.out.print("Equivalent Word/Name in Uppercase : "
+strLower);
}
}

47
2. to compare two strings
1. import java.util.Scanner;
2.
3. class CompareStrings
4. {
5. public static void main(String args[])
6. {
7. String s1, s2;
8. Scanner in = new Scanner(System.in);
9.
10. System.out.println("Enter the first string");
11. s1 = in.nextLine();
12.
13. System.out.println("Enter the second string");
14. s2 = in.nextLine();
15.
16. if (s1.compareTo(s2) > 0)
17. System.out.println("The first string is greater than
the second.");
18. else if (s1.compareTo(s2) < 0)
19. System.out.println("The first string is smaller than
the second.");
20. else
21. System.out.println("Both the strings are equal.");
22. }
23. }

c) Discuss briefly about string class.

Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

48
The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

QUESTION NO. 2)
a) What is an abstract class? Explain with an example program.

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It cannot
be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Abstract class Example


//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

49
public void sound(){
System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}

b) Write a program to implement the Fibonacci series using for loop control structure.

1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}

c) What are the Break and Continue statements?

Break:
The break statement in Java programming language has the following two
usages −

 When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following
the loop.

 It can be used to terminate a case in the switchstatement (covered in the next


chapter).

50
Syntax:
The syntax of a break is a single statement inside any loop −
break;

Continue:
The continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.

 In a for loop, the continue keyword causes control to immediately jump to the
update statement.

 In a while loop or do/while loop, control immediately jumps to the Boolean


expression.

Syntax:
The syntax of a continue is a single statement inside any loop −
continue;

QUESTION NO. 3)
a) Explain Method overloading and method overriding with suitable examples.

Method Overloading:
Overloading allows different methods to have same name, but different signatures
where signature can differ by number of input parameters or type of input parameters or
both. Overloading is related to compile time (or static) polymorphism.
Example:

public class Sum {

// Overloaded sum(). This sum takes two int parameters


public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);

51
}

// Overloaded sum(). This sum takes two double parameters


public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Method Overriding:
Declaring a method in sub class which is already present in parent class is known as
method overriding. Overriding is done so that a child class can give its own
implementation to a method which is already provided by the parent class. In this case
the method in parent class is called overridden method and the method in child class is
called overriding method.

Example:

class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}

52
b) Write a program to create two threads, one thread will print odd numbers and second
thread will print even numbers between 1 to 20 numbers.

public class Mythread {

public static void main(String[] args) {


Runnable r = new Runnable1();
Thread t = new Thread(r);
t.start();
Runnable r2 = new Runnable2();
Thread t2 = new Thread(r2);
t2.start();
}
}

class Runnable2 implements Runnable{


public void run(){
for(int i=0;i<21;i++){
if(i%2 == 1)
System.out.println(i);
}
}
}

class Runnable1 implements Runnable{


public void run(){
for(int i=0;i<21;i++){
if(i%2 == 0)
System.out.println(i);
}
}
}

c) Which statements are used for exception handling? Write down their syntax.

Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

Exception Handling Statements

Three statements play a part in handling exceptions:

Try:

The try statement identifies a block of statements within which an exception might be thrown.

53
Catch:
The catch statement must be associated with a try statement and identifies a block of
statements that can handle a particular type of exception. The statements are executed if an
exception of a particular type occurs within the try block. There can be as many statements
following a try statement as needed. Each statement handles any and all exceptions that are
instances of the class listed in parentheses, of any of its subclasses, or of a class that
implements the interface listed in parentheses.

Finally:
The finally statement must be associated with a try statement and identifies a block of
statements that is executed regardless of whether or not an error occurs within the try block.
The finally statement is generally used to clean up after the code in the try statement. If an
exception occurs in the try block and there is an associated catch block to handle the exception,
control transfers first to the catch block and then to the finally block.

Here is the general form of these statements:

try {
statements
}
catch (ExceptionType1 name) {
statements
}
catch (ExceptionType2 name) {
statements
}
...
finally {
statements
}

54
JAVA – (6th – Jan – 2018)
Question 2
a) Different Data types in Java?
Ans.: Java is strongly type language so we have to define data types for implementation.

Boolean Data Type:The Boolean data type is used to store only two possible values: true
and false. This data type is used for simple flags that track true/false conditions. The Boolean
data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
Byte Data Type: The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its default
value is 0.It saves space because a byte is 4 times smaller than an integer. It can also be used
in place of "int" data type.Example: byte a = 10, byte b = -20
Short Data Type:The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its default value is 0.A short data type is 2
times smaller than an integer and saves memory.Example: short s = 10000, short r = -5000
Int Data Type: The int data type is a 32-bit signed two's complement integer. Its value-range
lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its default value
is 0.The int data type is generally used as a default data type for integral values unless if there
is no problem about memory.Example: int a = 100000, int b = -200000
Long Data Type: The long data type is a 64-bit two's complement integer. Its value-range
lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -

55
1)(inclusive). Its default value is 0. The long data type is used when you need a range of
values more than those provided by int.Example: long a = 100000L, long b = -200000L
Float Data Type: float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of double) if you need to
save memory in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0d.Example: float f1 = 234.5f
Double Data Type:
The double data type is same as float data type but isa double-precision 64-bit IEEE 754
floating points. Its default value is 0.0d.Example: double d1 = 12.3
Char Data Type:The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.Example: char letter_A = 'A'.

b) What is BREAK statement in Java?


Ans.: When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop. And It
can be used to terminate a case in the switch statement.
c) Arrays can be defined in a different ways. Write them down.
Ans.: int[] a, b[]; it means a is int[], b is int[][] and int a[], b[]; and it means a is int[], b is
int[].

d) What is the difference between an array and a linked list?

Ans.: The difference between an array and a linked list is that an array is an index based data
structure, every element is associated with an index whereas the linked list is a data structure
that uses references, each node is referred to another node. In array size is fixed whereas
in link list size is not fixed.

Question 3:

a) Four main principles of OOPS language?

Ans.: There are four main OOP concepts in Java. These are:

 Abstraction. Abstraction means using simple things to represent complexity. We all


know how to turn the TV on, but we don’t need to know how it works in order to enjoy it.
In Java, abstraction means simple things like objects, classes, and variables represent
more complex underlying code and data. This is important because it lets avoid repeating
the same work multiple times.

56
 Encapsulation. This is the practice of keeping fields within a class private, then
providing access to them via public methods. It’s a protective barrier that keeps the data
and code safe within the class itself. This way, we can re-use objects like code
components or variables without allowing open access to the data system-wide.

 Inheritance. This is a special feature of Object Oriented Programming in Java. It lets


programmers create new classes that share some of the attributes of existing classes. This
lets us build on previous work without reinventing the wheel.

 Polymorphism. This Java OOP concept lets programmers use the same word to mean
different things in different contexts. One form of polymorphism in Java is method
overloading. That’s when different meanings are implied by the code itself. The other
form is method overriding. That’s when the different meanings are implied by the
values of the supplied variables.

b) What is Inheritance? Does Java support multiple inheritances?

Ans.: Inheritance is another labor-saving Java OOP concept. It works by letting a new class
adopt the properties of another. We call the inheriting class a subclass or a child class. The
original class is often called the parent. We use the keyword extends to define a new class
that inherits properties from an old class. Java supports multiple inheritances through
interfaces only. A class can implement any number of interfaces but can extend only one
class. Multiple inheritances are not supported because it leads to deadly diamond problem.

c) What is Polymorphism and what is the type of it?

Ans.: Polymorphism in Java works by using a reference to a parent class to affect an object in
the child class.

Types of Polymorphism:

In method overriding, the child class can use the OOP polymorphism concept to
override a method of its parent class. That allows a programmer to use one method in
different ways depending on whether it’s invoked by an object of the parent class or
an object of the child class.
 In method overloading, a single method may perform different functions depending
on the context in which it’s called. That is, a single method name might work in
different ways depending on what arguments are passed to it.
d) What is the method overriding? Can we override a static class?

Ans.: If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.Static methods cannot be
overridden because they are not part of the object's state. Rather, they belong to the class (i.e.
they are class methods).

57
Question 4:

a) Life cycle of an applet includes which steps?

Ans.: When an applet is executed within the web browser or in an applet window, it goes
through the four stages of its life cycle: initialized, started, stopped and destroyed. These
stages correspond to the applet methods init (), start (), stop () and destroy () respectively.

b) Which method is called by an applet class to load an image?

Ans.: getImage(URL object, filename) is used for this purpose.

c) Define code as an attribute of Applet?

Ans.: It is used to specify the name of the applet class.

d) Define canvas?

Ans.: It is a simple drawing surface which is used for painting images or to perform other
graphical operations.

Question 5:

a) Define Network Programming?

Ans.: It refers to writing programs that execute across multiple devices (computers), in which
the devices are all connected to each other using a network.

b) What is a Socket?

Ans.: 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.

c) Advantages & disadvantages of Java Sockets?

Ans.:

Advantages:Sockets are flexible and sufficient. Efficient socket based programming can be
easily implemented for general communications. It cause low network traffic.

Disadvantage:Socket based communications allows only to send packets of raw data between
applications. Both the
client-side and server-side have to provide mechanisms to make the data useful in any way.

58
d) Which class represents the socket that both the client and server use to communicate with
each other?

Ans.: java.net.Socket class represents the socket that both the client and server use to
communicate with each other.

Question 6:

a) What is JDBC (Java Database Connectivity)?

Ans.: Java Database Connectivity (JDBC) is an application programming interface (API)


which allows the programmer to connect and interact with databases. It provides methods to
query and update data in the database through update statements like SQL's CREATE,
UPDATE, DELETE and INSERT and query statements such as SELECT.

b) What is JDBC Driver?

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

 JDBC-ODBC bridge driver


 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)

c) What are the steps required to execute a query in JDBC?

Ans.: Following are the steps required to execute a query in JDBC:

 Load JDBC drivers.


 Register the driver with Driver Manager class.
 Open a connection.
 Create Statement object using connection object that enables to execute the query.

d)What is a database URL?

Ans.: A database connection URL is a string that your DBMS JDBC driver uses to connect to
a database. It can contain information such as where to search for the database, the name of
the database to connect to, and configuration properties.

☺THANK YOU ☺
59
60

You might also like