Oopj - Three Solved Model Set
Oopj - Three Solved Model Set
2. Describe the concepts of object and class with a suitable Java program?
Answer
• Class is the core of Java language.
• It can be defined as a template that describe the behaviors and states of a particular entity.
• A class defines new data type. Once defined this new type can be used to create object of
that type.
• Object is an instance of class.
• A class contain both data and methods that operate on that data.
• The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods.
• Thus, the instance variables and methods are known as class members.
Java class Syntax
JAVA PROGRAM
class Student
{ Student is a class
int roll_no = 5;
String name="ARYA"; Instance Variables
void info() Class members
{ method
System.out.println("Roll No: "+roll_no);
System.out.println("Name :" +name);
}
public static void main(String[] args)
{
Student myObj = new Student(); myObj is an object of
myObj.info(); class Student
}}
OUTPUT
Roll No: 5
Name : ARYA
• If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
• Implementation within the sub class overrides (replaces) the inherited implementation from
the parent class.
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass (Parent class).
• Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding
• The method must have the same name as in the parent class.
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Java Program to illustrate the use of Java Method Overriding
class Vehicle
{
void run() OUTPUT
•
If a variable is declared as final, they cannot change the value of final variable (It will be
constant).
• Syntax: final variable_name;
} System.out.println(obj.a=30);
class Demo1
{ ^
public static void main (String args[]) 1 error
{
A obj =new A ();
System.out.println(obj.a=30); }}
7. Distinguish the usage of “==” and equals() method when comparing String type?
== equals()
It is a operator It is a method
Used for for reference comparison (address Used for content comparison.
comparison)
== checks if both objects point to the same evaluates to the comparison of values in the
memory location objects.
// Java program to understand the concept of == operator and equals()
public class Test {
public static void main(String[] args) Output:
false
true
Downloaded from Ktunotes.in
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}}
Explanation:
• Here we are creating two objects namely s1 and s2.
• Both s1 and s2 refers to different objects.
• When we use == operator for s1 and s2 comparison then the result is false as both have different
addresses in memory.
• Using equals, the result is true because its only comparing the values given in s1 and s2
8. What are Collections in Java? Explain any one Collection interface in Java?
Answer
Collection Framework IN JAVA
• Java Collection means a single unit of objects.
• The java collections framework is a collection of interfaces and classes which help the
programmer to perform operations on data like sorting, searching, deleting, manipulating etc.
• Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
• The java.util package contains all the classes and interfaces for the Collection framework.
Hierarchy of Collection Framework:
List Interfaces
• In Java, the List interface is an ordered collection that allows us to store and access elements
sequentially.
• It extends the Collection interface.
• Classes that Implement List interfaces are:
§ ArrayList
§ LinkedList
§ Vector
§ Stack
Java ArrayList Class
• The ArrayList class of the Java collections framework provides the functionality of resizable-
arrays.
• It implements the List interface.
10. Explain JLabel component. With suitable examples explain any two of its constructors.
Answer
JLabel Constructors used are:
• JLabel(Icon ic)
• JLabel(String str)
• JLabel(String str,Icon ic,int align)
o Here Icon is abstract class that cannot be instantiated. OUTPUT
o ImageIcon is a class that extends Icon.
o So to load images the following statement can be used:
ImageIcon ic=new ImageIcon(“filename”);
where filename is a string quantity.
JLabel Example
import javax.swing.*;
public class SimpleLabel extends JFrame
{
SimpleLabel()
{
ImageIcon ic=new ImageIcon("C:\\Users\\kiran\\OneDrive\\Pictures\\Desktop\\KTU.jpg");
JLabel jl=new JLabel("KTU EMBLEM",ic,JLabel.LEFT);
setSize(350,350);
setVisible(true);
Part B
Answer any one question completely from each module.
11. (a) Describe in detail any three Object Oriented Programming principles. Illustrate with
suitable examples. (9)
Answer:
11 (b) What is Java Runtime Environment? What is the role of Java Virtual Machine in it? (5)
OR
Explain JVM Architecture?
Answer:
JAVA RUNTIME ENVIRONMENT
o JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.”
o The Java Runtime Environment provides the minimum requirements for executing a Java
application:
§ it consists of the Java Virtual Machine (JVM), core classes, and supporting files.
o The JRE is the software environment in which programs compiled for a typical JVM
implementation can run.
o The runtime system includes:
• Code necessary to run Java programs, dynamically link native methods, manage memory, and
handle exceptions.
• Implementation of the JVM
Role of Java Virtual Machine in JRE
Operation of JVM
JVM mainly performs following operations.
• Allocating sufficient memory space for the class properties.
• Provides runtime environment in which java bytecode can be executed
• Converting byte code instruction into machine level instruction.
JVM is separately available for every Operating System while installing java software so that JVM
is platform dependent.
12. (a) Compare and contrast Java standard edition and Java enterprise edition. (5)
Answer:
Java SE Java EE
1 Java or Java SE provides basic Java EE provides APIs for running large-scale
functionality like defining basic types applications.
and objects.
2 SE is a normal Java Specification. EE is built upon JAVA SE. Provides
functionalities like web applications, servlets etc
12)(b) Why is Java considered to be platform independent? What is the role of Bytecode in making
Java platform independent? (9)
Answer:
Java Bytecode
• Bytecode is program code that has been compiled from source code into low-level code
designed for a software interpreter.
• A popular example is Java bytecode, which is compiled from Java source code and can be run
on a Java Virtual Machine (JVM).
• Java bytecode is the instruction set for the Java Virtual Machine.
• It acts similar to an assembler which is an alias representation of a C++ code.
• As soon as a java program is compiled, java bytecode is generated.
• In more apt terms, java bytecode is the machine code in the form of a .class file.
• With the help of java bytecode, we achieve platform independence in java.
How does it work?
• When write a program in Java, firstly, the compiler compiles that program, and a bytecode is
generated for that piece of code.
• After the first compilation, the bytecode generated is now run by the Java Virtual Machine
and not the processor in consideration.
13. (a) Explain in detail the primitive data types in Java. (8)
Answer:
• Data type defines the values that a variable can take, for example if a variable has int data
type, it can only take integer values.
• Data types specify the different sizes and values that can be stored in the variable.
• There are two types of data types in Java:
§ Primitive data types
§ Non-primitive data types
13)(b) Explain automatic type conversion in Java with an example. What are the two conditions
required for it? (6)
Answer:
• When a data type is converted into another type is called type conversion(casting).
• When a variable is converted into a different type, the compiler basically treats the
variable as of the new data type.
• Type of Type Conversion in Java
1. Automatic Type Conversion/ Implicit Conversion/Widening
2. Explicit Type Casting/Narrowing
14. a) Using a suitable Java program explain the difference between private and public members in
the context of inheritance. (8 marks)
Answer:
• Inheritance is a mechanism of creating a new class from an existing class by inheriting the
features of existing class and adding additional features of its own.
• When a class is derived from an existing class, all the members of the superclass are
automatically inherited in the subclass.
• However, it is also possible to restrict access to fields and method of the superclass in the
subclass.
• This is possible by applying the access Specifiers to the member of the superclass.
• If a subclass needs to access a superclass member, give that member private access.
• The private members of the superclass remain private (accessible within the superclass only)
in the superclass and hence are not accessible directly to the members of the subclass.
• However, the subclass can access them indirectly through the inherited accessible methods of
the superclass.
Using the private access specifier
class Baseclass
14) b) Is it possible to use the keyword super within a static method? Give justification for your
answer. (6 marks)
Answer:
• A static method or, block belongs to the class and these will be loaded into the memory along
with the class.
• We can invoke static methods without creating an object. (using the class name as reference).
• Where, the "super" keyword in Java is used as a reference to the object of the super class.
• This implies that to use "super" the method should be invoked by an object, which static methods
are not.
• Therefore, it is not possible to use "super" keyword from a static method.
class SuperClass{
15) a) Explain in detail about byte streams and character streams with suitable code samples.(6
marks)
STREAM
• A stream is a sequence of data.
• In Java, a stream is composed of bytes.
• It's called a stream because it is like a stream of water that continues to flow.
• In Java, 3 streams are created for us automatically.
• All these streams are attached with the console.
4. System.out: standard output stream
§ System.out normally outputs the data that writes to it to the console / terminal.
§ Example: System.out.println("simple message");
5. System.in: standard input stream
§ which is typically connected to keyboard input of console programs.
§ Example:int i=System.in.read(); //returns ASCII code of 1st character
6. System.err: standard error stream
§ works like System.out except it is normally only used to output error texts.
§ Example: System.err.println("error message");
Types of Streams
• Depending upon the data a stream holds, it can be classified into:
1. Byte Stream
2. Character Stream
1. Byte Stream
• Byte stream is used to read and write a single byte (8 bits) of data.
• All byte stream classes are derived from base abstract classes
called InputStream and OutputStream.
a) Java InputStream Class
• The InputStream class used for byte stream-based input operations.
b) Java OutputStream Class
• OutputStream class used for byte stream-based output operations.
15) b) Describe in detail about exception handling, try block and catch clause with the help of a
suitable Java program.(8 marks)
• 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 is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
• The core advantage of exception handling is to maintain the normal flow of the application.
• An exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Java Exceptions
• There are mainly two types of exceptions:
o checked and
o unchecked.
• Here, an error is considered as the unchecked exception.
• According to Oracle, there are three types of exceptions:
1. Checked Exception
• The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions.
• e.g. IOException, SQLException etc.
• Checked exceptions are checked at compile-time.
2. Unchecked Exception
• The classes which inherit RuntimeException are known as unchecked exceptions
• e.g. ArithmeticException, NullPointerException,
• Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3. Error
• Error is irrecoverable
• e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java try- catch block
• The try statement allows you to define a block of code to be tested for errors while it is
being executed.
• The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
• The try and catch keywords come in pairs.
Syntax of Java try-catch
try
{
Block of code that may throw an exception
}
catch(Exception e)
{
Block of code to handle errors
}
Consider the following program: Problem without exception handling
Example
public class TryCatchExample1 {
OUTPUT
public static void main(String[] args) {
int data=50/0; //may throw exception Exception in thread "main" java.lang.ArithmeticException: / by zero
System.out.println("rest of the code"); at TryCatchExample1.main(TryCatchExample1.java:5)
}}
Solution by exception handling using try-catch block
public class Main
{ OUTPUT
public static void main(String[] args)
{ Exception Occurred
try REST OF THE CODE
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
16.(a) Explain object streams in Java. Explain the role of Serializable interface with a
suitable code sample.(8 marks)
• Serialization in Java is the process of converting the Java code Object into a Byte Stream, to transfer
the Object Code from one Java Virtual machine to another and recreate it using the process of
Deserialization.
• Most impressive is that the entire process is JVM independent, meaning an object can be serialized on
one platform and deserialized on an entirely different platform.
• For serializing the object, we call the writeObject() method of ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
Advantages of Java Serialization
• It is mainly used to travel object's state on the network (which is known as marshaling).
ObjectOutputStream class
•The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream.
• Only objects that support the java.io.Serializable interface can be written to streams.
Important Methods
Method Description
ObjectInputStream class
• An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Important Methods
Method Description
In this example, we are going to serialize the object of Student class. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of
the object in the file named f.txt.
import java.io.*;
class Persist{ OUTPUT
public static void main(String args[]){ success
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}}
16 (b) Explain throw, throws and finally constructs with the help of a Java program.(6 marks)
Java finally block
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
Case 3
Java finally example where exception occurs and
handled.
OUTPUT
public class CASE3{ HANDLED EXCEPTION
public static void main(String args[]){
try{ finally block is always executed
int data=25/0;
rest of the code...sss
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println("HANDLED EXCEPTION");
}
finally{System.out.println("finally block is always
executed");}
System.out.println("rest of the code..."); }}
System.out.println("normal flow...");
}
}
17. (a) Describe in detail the creation of a thread using the Runnable interface and the Thread class
with suitable examples. (10 marks)
Creating a Thread
• Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread class:
• Thread class provide constructors and methods to create and perform operations on a
thread.
• Commonly used Constructors of Thread class:
• Thread ()
• Thread (String name)
• Thread (Runnable r)
• Thread (Runnable r, String name)
• Thread class extends Object class and implements Runnable interface.
• Commonly used methods of Thread class:
• public void run (): is used to perform action for a thread.
• public void start (): starts the execution of the thread.
• JVM calls the run () method on the thread
1. By extending the thread class
• Create a new class that extends Thread and create an instance of that class.
Steps
1. Use a run() method which is initiated by start() method
class A extends Thread
{
public void run()
{
}
}
2. Invoking the run() method
• Creating the object of the corresponding thread class in the main() method class.
Thread_classname objName = new Thread_classname();
objName.start(); // invokes run() method
The ArrayList class provides various methods to perform different operations on arraylists.
1. Add elements:
§ add (): To add a single element to the arraylist
2. Access elements
§ get (): to access an element from the arraylist
3. Change elements
§ set (): To change element of the arraylist
4. Remove elements
§ remove (): to remove an element from the arraylist
Creating an ArrayList
class Main
{
public static void main(String[] args) OUTPUT
{
EVEN ArrayList: [0, 2, 6, 8, 10]
// create ArrayList Updated EVEN ArrayList: [0, 2, 4, 6, 8, 10]
ArrayList<Integer> A = new ArrayList<>(); Element at index 3: 6
Updated EVEN ArrayList: [0, 2, 4, 12, 8, 10]
// Add elements to ArrayList : add() Updated EVEN ArrayList: [0, 2, 4, 8, 10]
A.add(0);
A.add(2);
A.add(6);
A.add(8);
A.add(10);
System.out.println("EVEN ArrayList: " + A);
Exceptions
1. ArrayIndexOutOfBoundsException
18. (a) Explain in detail the Delegation Event model for event handling in Java?
EVENT HANDLING
• Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs.
• This mechanism has the code which is known as event handler that is executed when an
event occurs.
• Java Uses the Delegation Event Model to handle the events.
• This model defines the standard mechanism to generate and handle the events.
Creating a Thread
• Threads can be created by using two mechanisms:
3. Extending the Thread class
4. Implementing the Runnable Interface
Thread class:
• Thread class provide constructors and methods to create and perform operations on a
thread.
• Commonly used Constructors of Thread class:
• Thread ()
• Thread (String name)
• Thread (Runnable r)
• Thread (Runnable r, String name)
• Thread class extends Object class and implements Runnable interface.
• Commonly used methods of Thread class:
• public void run (): is used to perform action for a thread.
• public void start (): starts the execution of the thread.
• JVM calls the run () method on the thread
2. By extending the thread class
• Create a new class that extends Thread and create an instance of that class.
• The extending class must override the run() method -à entry point for the new thread
• It must also call start() ---à to begin execution of the new thread.
Steps
1. Use a run() method which is initiated by start() method
class A extends Thread
{
public void run()
}
}
2. Invoking the run() method
• Creating the object of the corresponding thread class in the main() method class.
Thread_classname objName = new Thread_classname();
objName.start(); // invokes run() method
19. (a) Write a Java program to demonstrate the use of JLabel and JButton by adding them to
JFrame.
import javax.swing.*;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame");
JLabel label = new JLabel("JLabel",JLabel.LEFT);
JButton b=new JButton("JButton");
19(b) Explain step-by-step procedure of using Java DataBase Connectivity in Java programs.
Java DataBase Connectivity (JDBC)
• JDBC stands for Java Database Connectivity, which is a standard Java API (Application
Programming Interface) for database-independent connectivity between the Java
programming language and a wide range of databases.
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
1. Register the Driver class
• The forName() method is used to register the driver class.
2. Create connection
• The getConnection() method of DriverManager class is used to establish connection
with the database.
3. Create statement
• The createStatement() method of Connection interface is used to create statement.
• The object of statement is responsible to execute queries with the database.
4. Execute queries
• The executeQuery() method of Statement interface is used to execute queries to the
database.
• This method returns the object of ResultSet that can be used to get all the records of a
table.
5. Close connection
• By closing connection object statement and ResultSet will be closed automatically.
• The close () method of Connection interface is used to close the connection.
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to follow 5 following steps.
• In this example we are using MySQL as the database.
• So need to know following information’s for the MySQL database:
1. Driver class: The driver class for the MySQL database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database.
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
// STEP 1: Register the Driver class
Class.forName("com.mysql.jdbc.Driver");
//STEP 2: Create connection
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","roo
t","root");
//here sonoo is database name, root is username and password
//STEP 3: Create statement
emp
Statement stmt=con.createStatement();
//STEP 4: Execute queries Name Age
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()) // Extract data from result set Poornima 29
System.out.println(rs.getString(1)+ " "+rs.getInt(2));
//STEP 5: Close connection Sangeeth 32
con.close(); Pratheesh 30
}catch(Exception e){ System.out.println(e);}
}
}
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Java JTextField Example
import javax.swing.*;
class TextFieldExample
{ OUTPUT
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("SWING Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
20(b) Write a Java Program to create a student table and to add student details to it using
JDBC.
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
6. What are packages? Write the steps involved in creating a package in java?
Answer
• A java package is a group of similar types of classes, interfaces and sub-packages.
• Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
• Advantage of Java Package
a. Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
b. Java package provides access protection.
c. Java package removes naming collision.
d. Reusability of code
Steps involved in creating a package
1. Declare the package at the beginning of the file using ‘package’ keyword
a. Syntax : package package_name;
2. Define a class inside the package and declare it as a public class.
3. Create a subdirectory under the directory where the source files are stored.
4. Store the classname.java file in the subdirectory.
5. Compile the file. It creates a.class file and is stored in the subdirectory.
PART B
11. Represent the following entities using UML class diagram.
a. Book b. Employee c. Vehicle
Answer:
class A
{
PROGRAM
class Area
{
int length, breadth;
Area (int l, int b)
{
System.out.println("Parameterized Constructor is automatically called");
length = l;
breadth = b;
}
void calc () OUTPUT
{
int A = length * breadth; Parameterized Constructor is automatically called
System.out.println(A); 600
}
}
class BoxDemo
{
public static void main (String args [])
{
Area mybox1 = new Area (20,30);
mybox1.calc();
}}
15. What is an exception? What are the categories of exceptions? Also discuss the advantages
of exception handling in Java.
Answer:
What is Exception?
• Exception is an abnormal condition.
• In Java, an exception is an event that disrupts the normal flow of the program.
• It is an object which is thrown at runtime.
• 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 is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
• The core advantage of exception handling is to maintain the normal flow of the application.
• An exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Java Exceptions
• There are mainly two types of exceptions:
o checked and
o unchecked.
Keyword Description
16. Discuss the concept of Interfaces and the types of interfaces in Java with example.
Answer:
INTERFACE IN JAVA
Syntax:
interface interface_name
{
variable declaration;
method declaration; // abstract methods having declarations only
}
Variable declaration:
static final type variable_name = value;
• type : datatype can be int, float…..
Eg: static final int A = 10;
Method Declaration :
return_type method_name(parameter list);
• Return_type : data type can be int, float…..
• Have only declaration and no body
Eg: int sum(int a , int b);
Example:
interface Area
{
final static float pi =3.14;
float compute (float x, float y);
}
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Types Of Interface
A
1. Interface can also be extended (Extending Interfaces)
Syntax: Example:
interface child_class extends parent_class
{ interface B extends A B
body of child_class
} {
2. Implementing Interfaces
Syntax: body of B
class class_name implements interface_name
{ }
body of class_name
PROGRAM
A class implements an interface, but one interface extends another interface.
interface Printable
{
void print();
} Printable
interface Showable extends Printable
{
void show(); extends
}
class Main implements Showable Showable
{
public void print()
{ OUTPUT
System.out.println("Hello"); Showable
} Hello
public void show() Welcome
{ implements
System.out.println("Welcome");
} Main
public static void main(String args[])
{
Main obj = new Main();
obj.print();
obj.show();
}}
17. Discuss the thread model / life cycle with suitable figure?
Answer:
Life cycle of a Thread (Thread States)/Java Thread Model
• A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies.
• A thread can be in one of the five states.
• 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
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.
18. Write a java program to create two threads, one for writing odd numbers and another for
writing even numbers up to 100 in two different files.
ANSWER:
class Runnable1 implements Runnable
{
public void run()
{
for (int i=0;i<100;i++)
{
if (i%2 == 1)
System.out.println(“ODD Numbers are:” +i );
}
}
}
19. What are layout managers? Explain any one layout manager with an example?
Answer:
• Layout refers to the arrangement of components within the container.
• The task of laying out the controls is done automatically by the Layout Manager.
o Automatically positions all the components within the container.
• Properties like size, shape, and arrangement varies from one layout manager to the other.
• LayoutMananger is an interface which implements the classes of the layout manager.
• There are following classes that represents the layout managers:
1. java.awt.GridLayout
2. java.awt.BorderLayout
3. java.awt.FlowLayout
4. javax.swing.BoxLayout
5. javax.swing.GroupLayout
6. javax.swing.ScrollPaneLayout
7. javax.swing.SpringLayout
2. Java GridLayout
• The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
• Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.setLayout(new GridLayout(2,2));
//setting grid layout of 2 rows and 2 columns
20. Discuss the different steps involved in establishing a JDBC connectivity and query
processing with a suitable example.
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
1. Register the Driver class
2. Create connection.
3. Create statement.
4. Execute queries.
5. Close connection
1. Register the Driver class
• The forName() method is used to register the driver class.
2. Create connection
• The getConnection() method of DriverManager class is used to establish connection
with the database.
3. Create statement
• The createStatement() method of Connection interface is used to create statement.
• The object of statement is responsible to execute queries with the database.
4. Execute queries
• The executeQuery() method of Statement interface is used to execute queries to the
database.
• This method returns the object of ResultSet that can be used to get all the records of a
table.
5. Close connection
• By closing connection object statement and ResultSet will be closed automatically.
• The close () method of Connection interface is used to close the connection.
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to follow 5 following steps.
• In this example we are using MySQL as the database.
• So need to know following information’s for the MySQL database:
1. Driver class: The driver class for the MySQL database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
• In this example, sonoo is the database name, root is the username and password both.
• First create a table in the mysql database, but before creating table, we need to create database first.
o create database sonoo;
o use sonoo;
o create table emp(id int(10),name varchar(40),age int(3));
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try
{
// STEP 1: Register the Driver class
Class.forName("com.mysql.jdbc.Driver");
//STEP 2: Create connection
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","roo
t","root");
//here sonoo is database name, root is username and password
//STEP 3: Create statement
Statement stmt=con.createStatement();
//STEP 4: Execute queries
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()) // Extract data from result set
System.out.println(rs.getString(1)+ " "+rs.getInt(2));
//STEP 5: Close connection
emp
con.close();
Name Age
}catch(Exception e){ System.out.println(e);}
} Poornima 29
}
Sangeeth 32
Pratheesh 30
PART A
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
OUTPUT
29 is a prime number.
2. What are bytecodes and JVM? Explain how Java implements Machine Independent
Programming?
ANSWER:
• Bytecode is program code that has been compiled from source code into low-level
code designed for a software interpreter. ...
• A popular example is Java bytecode, which is compiled from Java source code and
can be run on a Java Virtual Machine (JVM).
What is JVM? Java Virtual Machine (JVM) is a engine that provides runtime environment to drive
the Java Code or applications. It converts Java bytecode into machines language. JVM is a part of
Java Run Environment (JRE). In other programming languages, the compiler produces machine code
for a particular system. However, Java compiler produces code for a Virtual Machine known as Java
Virtual Machine.
Keyword Description
6. Write a Java program that read from a file and write to file by handling all file related
exceptions using FileReader and FileWriter classes.
ANSWER
import java.io.*;
class Main
{
public static void main(String a[]) throws IOException
{
try
{
FileReader f1= new FileReader("test.txt");
FileWriter f2= new FileWriter("cp.txt");
int c;
2) String is slow and consumes more memory when you StringBuffer is fast and consumes
concat too many strings because every time it creates less memory when you cancat
new instance. strings.
3) String class overrides the equals() method of Object StringBuffer class doesn't
class. So it is possible to compare the contents of two override the equals() method of
strings by equals() method. Object class.
8. Listthe
Using anyString
five event
Classsources and their correspondingUsing
eventthe
types and listeners
StringBuffer used.
Class
ANSWER:
class Main class Main
{ {
public static void main(String args[]) public static void main(String args[])
{ {
String s1=new String("Sachin"); StringBuffer s1=new StringBuffer("Sachin");
s1.concat(" Tendulkar"); s1.append(" Tendulkar");
System.out.println(s1); System.out.println(s1);
} }
} }
OUTPUT OUTPUT
Model-View-Controller Architecture
• Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each
of its components
• Essentially, MVC breaks GUI components into three elements.
• Each of these elements plays a crucial role in how the component behaves.
• The Model-View-Controller is a well-known software architectural pattern ideal to implement
user interfaces on computers by dividing an application intro three interconnected parts
PART B
11. Construct Use Case diagrams for the following:
a. ATM b. Library c. Railway reservation
ANSWER:
Comments
• A comment is a non-executable statement that helps to read and understand a program
especially when your programs get more complex.
• Java programming language supports three types of comments.
o Single line (or end-of line) comment: It starts with a double slash symbol (//) and
terminates at the end of the current line. The compiler ignores everything from // to the
end of the line. For example:
// Calculate sum of two numbers
o Multiline Comment: Java programmer can use C/C++ comment style that begins with
delimiter /* and ends with */. All the text written between the delimiter is ignored by
the compiler. This style of comments can be used on part of a line, a whole line or more
commonly to define multi-line comment. For example.
/*calculate sum of two numbers */
o Documentation comments: This comment style is new in Java. Such comments begin
with delimiter /** and end with */. The compiler also ignores this type of comments
just like it ignores comments that use / * and */. The main purpose of this type of
comment is to automatically generate program documentation. The java doc tool reads
these comments and uses them to prepare your program's documentation in HTML
format. For example.
/**The text enclosed here will be part of program documentation */
14. Describe the control statements in JAVA?
ANSWER:Refer notes of Module 2
15. Write a Java program that accepts N integers through console and sort them in ascending
order.
ANSWER:
import java.util.Scanner;
public class Ascending _Order
{
16. Explain in detail how exception handling mechanism used in Java using throw and
throws?
ANSWER:
Java throw keyword
• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception in java by throw keyword.
• The syntax of java throw keyword is given below.
throw exception;
public class MyClass {
OUTPUT
static void checkAge(int age) {
if (age < 18) { Exception in thread "main"
throw new ArithmeticException("Access denied - You must be java.lang.ArithmeticException: Access denied -
at least 18 years old."); You must be at least 18 years old.
}
else { at MyClass.checkAge(MyClass.java:4)
System.out.println("Access granted - You are old enough!");
}} at MyClass.main(MyClass.java:12)
System.out.println("normal flow...");
}}
4) Throw is used within the Throws is used with the method signature.
method.
this.t=t; 400
} 500
t.printTable(5); 20
}} 25
18. Discuss any five methods used for string processing in Java with examples?
ANSWER
1. STRING LENGTH (length())
• The java string length () method gives length of the string.
• It returns count of total number of characters.
• Syntax: length();
Java program illustrating the use of String Length : length()
class Main
{
public static void main(String args[])
OUTPUT
{ Length of S1 is :14
String S1 = "JAVA IS SIMPLE"; Length of S2 is :16
String S2 = "JAVA IS POWERFUL";
int len1 = S1.length(); // returns the no of characters in the string S1
int len2 = S2.length();
System.out.println("Length of S1 is :" +len1); //14
System.out.println("Length of S2 is :" +len2); //16
}}
2. Java string equals()
o method compares the two given strings based on the content of the string. If any
character is not matched, it returns false. If all characters are matched, it returns true.
o Syntax:
§ S1.equals(S2)
• Returns true if S1=S2
Java String equalsIgnoreCase()
20. Explain the steps using for connecting a Java program to a database using JDBC API
with á proper example.
ANSWER
Refer note of Module 5