Java Programming
Java Programming
SECTION A SECTION B
UNIT CHAPTER
2 MARKS 10 MARKS
Introduction to JAVA 1 -
Inheritance - 1
II
Arrays, Strings and Vectors 1 1
Wrapper Class - -
Interfaces 1 1
III Packages 1 1
Multithreaded Programming: 1 2
Managing Exceptions 1 1
IV
Applet Programming 1 2
Graphics Programming 1 2
V
Managing Input/Output Files in JAVA 1 1
TOTAL 12 16
TOTAL MARKS 20 50
SEC
T
1. What is concurrency? –
SECTI
O
1. What is exception? –
A
(
2
M
a
r
k
s
)
U
N
I -
T I
V
2. How user defined exception is done?
3. Write down the applet code for “hello-class”file?
4. Why repaint () method is used?
SEC
T
I
[ Nov / Dec 2015 ]
O
N
–
A
(
2
M
a
r
k
s
)
U
N
I
T
-
V
1. What is the difference between character oriented and byte oriented streams?
2. What is stream? How stream are classified?
3. What is the use of Graphic class?
SEC
T
1. What is package? Write down the steps for creating user defined package.
2. What is thread ?explain thread cycle with neat diagram.
3. What is interface? Write a program to demonstrate interface.
2. Write down the default values of byte and char data types?
⮚ The default value of byte=0
⮚ The default value of char=NULL CHARACTER
5. What is the use of ‘this’ and ‘super’ keyword? Ans. Use of ‘this’ keyword:
Ans. Multiple inheritance in Java programming is achieved or implemented using interfaces. Java does not support multiple inheritances using
classes.A class can extend only one class but it can implement multiple interfaces.
7. What is concurrency?
Ans. Concurrency is the ability to run several programs or several parts of a program in parallel. The backbone of java concurrency is threads. A
thread is a lightweight process which has its own call stack, but can access shared data of other threads in the same process.
8. What is exception?
Ans. An exception is an error that occurs at run time.
import java.applet.Applet;
import java.awt.Graphics;
public class HelloCLASSApplet extends Applet
{
public void paint(Graphics g){ g.drawString("Hello CLASS", 50, 50);
}
}
13. Mention the ways of implementing multithreading in Java? Ans. The ways of implementing multithreading in Java are:
⮚ Extends Thread class. Create a thread by a new class that extends Thread class and create an instance of that class.
⮚ Implementing the runnable interface. The easiest way to create a thread is to create a class that implements the runnable interface.
14. Mention any four thread methods? Ans. Thread methods are:
⮚ start()
⮚ run()
⮚ yield()
⮚ wait()
Ans. Java is one of the simple programming language because java removes some complex concept like pointer and execution time will be
less.
Reasons:-
⮚ Much easier to write bug free code.
⮚ Java has considerably more functionality than c.
switch(expression)
{
Case value1: Case value2: b
………. default: r
}
e
;
19. What is instance variable? Give an example. Ans.
⮚ Instance variables are declared in a class , but outside a method. They are also
called member or field variables.
⮚ Instance variables are created when an object is created and destroyed when the object is destroyed.
Ans. Constructor with no arguments is called as default constructor The default constructor is useful to initialize all objects with
same data. Ex:
A()
{
}
Ans. Errors are related to errors that occur in the java virtual machine itself, and not in a program. These types of exceptions are beyond our
control, and a program will not handle them.An exception is an error which can be handled .An error is an error which cannot be handled.
26. What is the purpose of ‘init ()’ method in applet?
30. What are the default values of float and char primitive data types in java? Ans.
● Default value of float =0.0f
● Default value of char = NULL CHARACTER
Ans. Labeled break: the break statement breaks out the closest loop or switch statement.
Ex: for(int i=0;i<10;i++){ while(true){
break;
}
}
Labelled continue: the continue statement transfers the control to the closest enclosing loop.
Ex: for(int i=0;i<10;i++){
while(j<10){ if(j==5)
continue;
}
}
32. Define package. Mention its use.
Ans. Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for preventing naming
conflicts.
A constructor name should be always The method and class name can be same
same as class name or different
36. Difference between class and abstract class?
Class Abstract class
The class does not contain It contains abstract methods
abstract methods
The class can be instantiated Abstract classes cannot be instantiated
⮚ CurrentThread()
⮚ getName()
⮚ run()
⮚ sleep()
⮚ Private
⮚ Default
⮚ Protected
⮚ Public
42. Define a stream in java. Briefly mention the broad classification of java stream classes? Ans. A stream can be defined as a sequence of data. The input
stream is used to read data from a source and the Output Stream is used for writing data to a destination.
43. How applets differ from applications?
Ans. The main difference between Applet and Application is that the applet is a small java program that can be executed by a Java-compatible
web browser while
the application is a standalone program that can directly run on the machine.
Ans. super : it is used to call the constructors of super class. this : it is used to call the constructors of same class.
It is slow and consumes more memory It is fast and consumes less memory
5 MARKS QUESTIONS
1. Explain the features of java? Ans: Features of java are:
● Simple: Easy to learn. Because java inherits the c/c++ syntax and many of the
object oriented features of c++.
● Secure: Java provides a firewall between a networked application and user computer.
● Portable: Translating a java program into bytecode makes it much easier to run a program in a wide variety of environments.
● Object oriented: Java enhances and refines the object oriented paradigm used by C++. The object model in java is simple and easy to extend.
● Robust: Java eliminates memory management problems by managing memory allocation and deallocation.
● Multithreaded: Java supports multithreaded programming which allows you to write programs that do many things simultaneously.
● Dynamic: Java programs have run time information that is used to verify and resolve accesses to objects at run time.
● Distributed: Java is designed for the distributed environment of the internet, because it handles TCP/IP protocols.
● Interpreted and Performance: Java bytecode can be interpreted on any system that provides a high JVM. Java is well designed to perform
well on very low power CPUs.
● Architecture Neutral: Java programs can be executed on any processors like Pentium, Celeron, dual core, AMD and so on,hence it is called
architecture neutral.
2. What are static variables and static methods? Ans: Static variables:
● The instance variables are non-static and it is part of an object. But static variables are special type of variables that are not associated with
an object, they are associated with class.
● The static variables are also called as class variables.
● The static variables can be accessed without an object.
● A static variable can be accessed directly by the class name and does not need any object.
Syntax: <class_name>.<variable_name>
Example:
class staticdemo{ int x,y;
static int z;
System.out.println(staticdemo.z);
}
Static Methods:
● The methods can also be declared as static. A static method is associated with a class rather than the instances.
● The static methods are also called as class members.
● The most common example of a static member is main(). The main() is declared as static because it must be called by the operating
systemwhen our program begins.
● A static methods can be accessed directly by the class name and does not need any object.
Syntax:
<class_name>.<method_name>(arguments)
Example:
staticdemo.method1();
Declaration:
class staticdemo{ int x,y;
static int z;
}
3. Explain any three string methods with example?
● concat(): This method creates a new string by appending the contents of string object passed as arguments to the contents of string on which
the method is invoked.
Example:
publicString concat(String str) String str=”Skyward”;
System.out.println(str.concat(“Publishers”)); //”Skyward Publishers” is printed.
● replace(): This method creates a new string using the same contents as that of the string object on which the method is invoked.
Example:
public String replace(char old,char new) String original=”Java ProgrAmming”;
System.out.println(original.replace(‘a’,’o’)); //”Javo Programming” is printed.
● substring(): The substring method creates a new string using partial contents of the string on which it is invoked. This method has two
overloaded version.
Example:
public String substring(int begin)
public String substring(int begin,int end) String original=”watermelon”;
System.out.println(original.substring(5)); // prints “rings”
4. Differentiate between arrays and vectors? Ans:
Public: The public modifiers is the least restrictive of all access modifiers. It can apply it to a class, its methods and its member variables. A public
class can be instantiated without any restrictions.
EXAMPLE:
package pack; public class A{
public void msg(){System.out.println(“Hello”);}
}
//save by B.java
class B{
public static void main(String args[]){ A obj = new A();
Obj.msg();
}
}
6. What is Interface? Explain with an example how a class implements an interface.
Ans: An interface is a description of a set of abstract methods that is supported to be implemented by the classes. In an interface no method can
include a body. It specifies what can be done, but no implementation. Once an interface is defined any number of classes can be implemented. The
interface can be defined using the interface keyword.
Syntax:
interface interface_name { public static varibles public abstract methods
}
Example:
interface XYZ
{
public void functionx(); public void functiony();
}
class ABC implements XYZ
{
public void functionx() { } public void functiony() { }
}
7. Explain user defined exception in Java?
Ans: Java provides us facility to create our own exceptions which are basically derived classes of exception. Things to remember before writing an
exception
● All exceptions must be a child of Throwable
● To write a runtime exception, extend the RuntimeException class.
}
class MultipleThreads {
public static void main(String args[]) { ThreadA ta = new ThreadA(); ThreadB tb = new ThreadB();
ThreadC tc = new ThreadC();
Thread t1=new Thread(ta,”Thread One”); Thread t2=new Thread(tb,”Thread Two”); Thread t3=new
Thread(tc,”Thread Three”); t1.start();
t2.start();
t3.start();
for(int i=16;i<=20;i++) System.out.println(Thread.currentThread().getName()+”=”+i); System.out.println(“End of Main”);
}
}
9. Explain the cycle of thread with a neat diagram?
Ans: Start(): When the start() method is called, the thread enters in a ready- to- run state. This thread is now in the pool of threads ready for the
execution. Sometimes
later the thread is picked up by the scheduler for execution and moved to the running state.
● The thread scheduler may move the thread out of the running state even if it has not finished the execution.
Ready-to-run state(Runnable): A thread is in ready-to-run state when it is eligible to run, but the scheduler has not yet picked it to actually run. A
thread can also return to ready-to-run state either after running or after the not-ready-to-run state.
● Call the start() method only once on a thread object. Re invoking a start method on thread object that is already started is illegal.
Running: When the thread enters in this state, the JVM starts to execute the thread run() method. The thread remains in this state and keep running
until it is either swapped out by thread scheduler or it voluntarily give up its turn for some reasons.
Not-ready-to-run (Blocked state): A thread moves out of the running state when it is waiting for something to happen.
Sleeping: We may want a thread to do-nothing for some time. We can call Thread.sleep() method in the thread run() method. This method tells the
currently running thread to sleep for some period of time.
Waiting: Sometimes a thread might wait(), just because we have asked it to wait in its run method. In that case,the thread changes its state from
running to waiting .
Blocked: Sometimes a thread needs to wait for a resource while running. For instance ,if it is reading from a network resources in its run method, it
has to wait until that resource becomes available.
Dead state: A java thread enters this state when it has finished the execution of its run method. We cannot start the thread once it is dead. The
thread can be started only once in its life time. If we re-invoke start() on a thread which is dead,it does not start again. Using isAlive() method we can
test whether the thread is alive or dead.
10. Explain how parameters are passed to an applet?
Ans: Applet can get different input from the HTML file that contains the
<APPLET>tag through the use of applet parameter. To set up and handle parameters in the applet , we need two things:
1. A special parameter tag in the HTML file.
2. Code in our applet to read those parameters. Example:
import java.applet.Applet; import java.awt.Font; import java.awt.Graphics;
public class MyFontApplet extends Applet { String fontName;
int fontSize; public void init() {
fontName = getParameter(“font”);
fontSize = Integer.parseInt(getParameter(“size”));
}
Public void paint (Graphics g) {
Font f = new Font(fontName and fontSize); g.setFont(f);
g.drawString(“Skyward Publishers”,50,50);
}
}
11. Explain any seven methods of graphics class with an example for each? Ans:
METHODS DESCRIPTION
draw3Drect() Draws a 3-D rectangle
drawArc() Draws an arc
drawLine() Draws a line
drawOval() Draws an oval
fillArc() Draws a filled arc
fillOval() Draws a filled oval
fillRect Draws a filled rectangle
● Example for drawLine( ) import java.awt.Graphics;
public class DrawLineDemo extends java.applet.Applet { public void paint(Graphics g) { g.drawLine(25,25,75,75);
}
● Example for draw3Drect( ) import java.awt.Graphics;
public class DrawLineDemo extends java.applet.Applet { public void paint(Graphics g) {
g.draw3DRect(20,20,60,60,true); g.draw3DRect(120,20,60,60,false);
}
● Example for drawArc( ) and fillArc( ) import java.awt.Graphics;
public class DrawLineDemo extends java.applet.Applet { public void paint(Graphics g) {
g.drawArc (50,50,80,60,45,120); g.fillArc(150,50,80,60,45,120);
}
12. Explain the use of FileInputStream class and FileOutputStream class? Ans: Use of FileInputStream:
● A file is opened for input by creating a FileInputStream object. FileInputStream(String fileName) throws
FileNotFoundException
Here, filename specifies the name of the file you want to open. If the file does not exist, then FileNotFoundException is thrown.
Example:
FileInputStream fis; try {
fis = new FileInputStream(“myFile.dat”);
}catch(IOException) {
}
Use ofFileOutputStream:
● To open a file for output, create a FileOutputStream object. FileOutputStream(File file) throws FileNotFoundException
Here, creates a file output stream to write to the file represented by the specified file object. If the file cannot be created, then
FileNotFoundException is thrown.
Example:
File f = new File(“myFile.dat”); FileOutputStream fos;
try {
fos = new FileOutputStream(f);
}catch(IOException) {
}
13. Explain with example:
Method overloading: Method Overloading means to have two or more methods with same name in the same class with different arguments.
Example:
class Myclass {
public void getAmount (int rate) {….}
public void getAmount (int rate, long principal) {….}
}
Method overriding: Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of
its super class.
Example:
class Baseclass {
public void getAmount (int rate) {….}
}
class Myclass extends Baseclass{ public void getAmount (int rate) {….}
}
Abstract method: A method without body is known as abstract method. A method must always be declared in an abstract class.
Example:
abstract void method1(); // Abstract method
Abstract class: Abstract classes are classes that contain one or more abstract methods. Example:
abstract class Test { // Abstract class int a,b,c;
abstract void method1(); // Abstract method abstract void method2(); // Abstract method void
method3() {
}
}
14. Write a short notes on data output stream and data input stream? Input stream
● Input stream is an abstract class that provides the framework from which all the other input streams are derived
● We cannot create an instance of inputstream class as it is abstract class .
● Whenever we want to read the data in bytes format, then we use the input stream classes
● The inputsream class contains lot of methods for reading bytes , closing stream
,skipping part of data in the streams. finding the number of bytes present in the input data ,etc.
Output stream
● Output stream is an abstract class that provides the framework from which all other output streams are derived
● We cannot create an instance of outputstream class as it is abstract class
● Whenever we want to write data in byte format, then we use the output stream classes.
● The outputstream class contains lot of methods for writing bytes, closing streams
,etc.
}
● start( ): start( ) is automatically called to begin the execution of the applet. This method is called each time the applet is revisited by the user.
Syntax:
public void start( )
{
}
● stop( ): This method is called by the browser when an applet is to stopped. Syntax:
public void stop( )
{
}
● destroy( ): this method is called when an applet is being terminated from the memory. The stop( ) method will always be called before
destroy( ). The code related to releasing memory allocated to the applet should be done in this method.
Syntax:
public void destroy( )
{
}
17. Difference between JDK and JRE?
JDK JRE
JDK needs more disk space as it JRE is smaller than JDK so it needs less disk
contains JRE along with various
Development tools space
&binary AND operator copies a bit to the result if it Exists in both operands
^ binary XOR operator copies the bit if it is set in one Operand but not both
~ binary 1s complement operator is unary and has the Effect of negating bits
<<binary left shift operator . this left operands value is Moved left by the number of bits specified by the right
Operand
>>binary right shift operator . this left operands value is Moved right by the number of bits specified by the Right
Operand .
Overloading
1. Signature has to be different just a difference in return type is not enough.
2. Any access modifier can be used.
3. The methods exception list may vary freely
4. The method to be called will be decided at the time of compilation.
5. Methods can be static or non-static.
Over Ridding
1. Signature can be same.
2. Over ridding method cannot be more restrictive than the over ridden method.
3. Over ridding method may not throw more checked exceptions than the overridden method.
4. The method to be called will be decided at the time of run time based on type of the object.
5. Static method don’t participate in over ridding since they are resolved at compile time based on the type of reference variable.
23) How to create objects? What happens when you create objects?
An object is created by instantiating a class. The process of creating an object of a class is called as instantiation and created object is called as an
instance.
● To create a new object, java uses the new keyword
● The object are created using the new operator with the name of the class we want to create an instance of, then parentheses after that. The
general form of creating an object is
● When an object is created an instance of a class is created. Reference variable does not define an object but it is simply a variable that can
refer to an object. The new operator dynamically allocates memory for an object and returns a reference to it.
● Eg: Account acc = new Account();
Where Account is a class name, acc is reference variable and new is the operator to create an object. The Account object is created in the
heap memory. The address of that object is assigned to the reference variable acc. The reference variable is declared in the stack.
class Test
{
int a; int b;
Test(int a, int b)
{
this.a = a; this.b = b;
}
void display()
{
System.out.println("a = " + a + "b = " + b +);
}
● A container is a components that that can accommodate other components and also other containers.
● Containers provides the support for building complex hierarchical graphical user interface
● Container provides the overloaded methods add() to include components in the container
Logical operators return a true or false value based on the state of the variables. The logical operators are
&& (Short circuit If both the operands are non zero then ( A&&B ) is false
AND operator) the condition becomes true.
| (OR operator) If any of the two operands are non zero ( A|B ) is true
then the condition becomes true
|| (Short circuit OR If any of the two operands are non zero ( A||B ) is true
operator) then the condition becomes true.
^ (XOR operator) This return true only if its operand. If ( A^B ) is true
its operand are different otherwise
false.
! (NOT operator) Use to reverses the logical state of its !( A&&B ) is true
operand. If a condition is true then
logical NOT operator make false.
27. Illustrate array declaration and accessing data elements using an example.
Array is collection of elements of same type. The array stores a fixed-size sequential collection of elements of the same type.
Declaring an array
The array declaration is usually the data type followed by a pair of square brackets followed by the name of the array
Method
● A method is used for any general purpose tasks like calculations.
● The method name and class name can be same or different.
● A method can be called after creating the object.
● A method can be called any number of times on the object
● A method is executed only when we want it.
29) Explain try and catch with an example.
Ans. The core of exception handling is try and catch . these keywords works together. we cannot have a try without a try.
General form of the try/catch exception handling blocks
try
{
// do risky things
}
catch(Exception ex)
{
//try to recover
}
Try
A try block is simply the keyword try. followed by braces enclosing the risky code that can throw the exception.
try
{
}
Catch
A catch block consists of the keyword catch followed by a single parameter between parentheses that identify the type of exception that the block is
to deal with. this is followed by the code to handle the exception enclosed between braces
try{
}
catch(Exception ex){
}
try
{
K=i/j;
}
catch (ArithmeticException e)
{
System.out.println(“exception occurred: divition by zero”); K=i/(j+2);
}
c. This method is defined in component and returns a graphics object. Therefore, any class that is a subclass of component can be drawn upon.
The functionality of the graphics class can be accessed even though it is abstract class.
31) Write program to sort a list of elements in ascending order.
class sorting
{
public static void main(String args[])
{
int a[ ] = new int[5];
System.out.println(“ enter five elements \n”); for( int i=0;i<5;i++)
a[i]=Integer.parseInt(args[i]); System.out.println(“\n before sorting \n”);
for( int i=0;i<5;i++) System.out.print(“ “ +a[i]);
bubbleSort(a,5);
System.out.println(“\n\n after sorting \n”); System.out.println(“ Ascending order \n”);
for( int i=0;i<5;i++) System.out.print(“ “ +a[i]);
}
}
}
}
32) Give the steps to create and use a java package with an example. Ans.
● To create a package, put a package command at the top of a java source file. the classes declare within that file will then belong to the
specified package. Since a package defines a namespace, the names of the classes that we put into the file become part of that package’s
namespace.
● This is the general form of the package statement:
● Here, pkg is the name of the package. for example, the following statement creates a package called project1.
● Java uses the file system to manage packages, with each package stored in its own directory. for example, the class files for any classes we
declare to be part of pack1 must be stored in directory called pack1.
● Step1: create a program which is part of package called pack1
● Step2: the command is javac –d.packageExample.java. We can see that pack1
directory is automatically created by the compiler.
● Step3: create another file called packageDemo.java in pack2 package
● In this file, we are trying to import the pack1 classes and creating an object of
packageExample