java notes
java notes
SOLVED
PAST PAPERS
1
JULY 2016- Java
Question No 1(a)
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.
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?
Static or compile-time.
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
3(b): ANS:
importjava.util.Scanner;
publicclassPostive_Negative
4
{
int n;
Scanner s =newScanner(System.in);
n =s.nextInt();
if(n >0)
elseif(n <0)
else
two thirds.
Solution:
3(d):If x and y are Java variables of type double, write the Java code for
x2+ 2/ 3y-5
Solution:
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.
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:
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.
6
int cnt = 0;
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:
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.
9
Question#3;
package matrix;
import java.util.Scanner;
int n;
a[i][j] = input.nextInt();
}
}
{
for (int j = 0; j < n; j++)
10
b[i][j] = input.nextInt();
}
}
System.out.println("Multiplying the matrices...");
{
for (int j = 0; j < n; j++)
}
}
System.out.println();
input.close();
import java.util.Scanner;
11
class Binarysearch {
n = in.nextInt();
array[c] = in.nextInt();
search = in.nextInt();
first = 0;
last = n - 1;
first = middle + 1;
break;
else
last = middle - 1;
12
if (first > last) System.out.println(search + " isn't present in the list.\n");
}}
Write a complete java program to display 1to100 numbers.your program should invoke separate threads
package mythreads;
13
public class Mythreads
t.start();
t2.start();
for(int i=0;i<100;i++){
if(i%2 == 1)
System.out.println(i);
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.
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
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
Question no: 2
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
} System.out.println("Interrupted");
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?
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); }
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:
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.
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
Yes, we can declare main method as private. It compiles without any errors, but in
runtime, it says main method is not public.
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
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.
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 {
25
public void setEmpId(int empId) {
this.empId = empId;
}
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)
/*
* 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;
}
}
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;
}
}
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
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.
classLinkedList {
staticNode head;
staticclassNode {
intdata;
Node next;
Node(intd) {
data = d;
next = null;
}
}
31
Node current = node;
Node next = null;
while(current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
returnnode;
}
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 (i);
}
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;
b = (byte) i;
i = (int) d;
b = (byte) d;
i and b 257 1
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:
35
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5) continue;
System.out.print(i +" ");
}
}
}
try {
36
// exception handler for ExceptionType2
// ...
finally {
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:
37
JUNE 2013:
Write the output of the following program below, as it would appear on the console
38
mystery(name, money, a);
a.name = "Billy";
a.money++;
name = "Susan";
}}
String name;
int money;
this.name = name;
this.money = money;
}}
SOLUTION:
Susan, 30, Janet: $31
39
Susan, 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:
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;
}
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.
import java.util.Scanner;
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. }
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.
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.
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. }}
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.
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.
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:
51
}
// 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.
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.
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.
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'.
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:
Ans.: There are four main OOP concepts in Java. These are:
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.
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.
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.
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:
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.
d) Define canvas?
Ans.: It is a simple drawing surface which is used for painting images or to perform other
graphical operations.
Question 5:
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.
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:
Ans.: JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
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