Professional Documents
Culture Documents
Xii Important Questions With Solution Informatics Practices
Xii Important Questions With Solution Informatics Practices
1. Why do you use import statement in java programming? Explain with example.
Ans. The import statement in Java allows programmers to refer to classes which are declared in other
packages to be accessed without referring to the full package name. Import statement must be the first
line of the program. Import statement have 2 option for importing the classes from packages
a. single class from package by mentioning the class name specifically. Eg. import
javax.swing.jOptionPane;
b. entire class by using * (asterisk) symbol in place of class name. Eg. import javax.swing.*;
Classes from the java.lang package are automatically imported, so it is not require to explicitly
importing.
2. What will be the initial value of an object reference which is defined as an instance variable?
Ans. Each instance variable is initialized with a default value when it is created:
Type
Initial / Default value
Type
Initial / Default value
byte
0(Zero of byte type)
double
0.0D
short
0(Zero of byte type)
char
null character i.e., \u000
int
0
boolean
false
long
0L
All reference types
null
float
0.0F
3. What is the purpose of if statement? Describe the different forms of if statements with example.
Ans. An if-statement tests a particular condition; if the condition evaluates to true, a statement or set of
statements is executed otherwise the statement or set of statements is not executed.
There are four different forms of if statements which are as following:
1. Simple if statement: Example:
if(ch== )
label1.setText(It is space character);
2. If-else statement: Example:
if(num>0)
label1.setText(number is positive);
else
label1.setText(number is negative or zero);
3. Nested if statement:
if(num>0)
{
if(num<100)
label1.setText(number is between 0 to 100);
}
else
label1.setText(number is not between 0 to 100);
4. How can you describe the life of a variable in an application?
Ans. We can describe the life of a variable in an application by following two different ways:
1. Local variable: The variable which is declared inside a method and is only accessible inside that
CBSE CS N IP
Page 1 of 12
5.
Ans.
6.
Ans.
7.
Ans.
8.
Ans.
9.
Ans.
CBSE CS N IP
Page 2 of 12
Page 3 of 12
When we delete a container control, all its child controls automatically get deleted.
16. What is a list? How is it different from combo box?
Ans.
A List is a graphical control that displays a list of items in a box wherefrom the user can make
selections
Difference between List and ComboBox
List
ComboBox
A list doesnt have a text field the user can
A combobox is a cross between a text field
used to edit the selected item.
and a list.
In a list, the user must select items directly
In a combobox user can edit it if he/she
from the list.
whishes.
The list doesnt drop down.
A combobox takes less space initially but
drops down when user clicks on its arrow.
Lists allow us to select more than one item.
Combobox allows only single item
selection.
17. What do you mean by life time of variable? How is a local variable different from other variable?
Ans.
The lifetime of variable is the period during which it can be accessed.
A local variable is declared inside a method and is accessible only inside that method. In this
way local variable is different from other variable.
18. What is the purpose of default clause in a switch statement?
Ans. Default is used for the else situation. The default statement gets executed when no match is found.
19. While working in NetBeans, Raj included a Listbox in the form. Now she wants the list of her friend's
names to be displayed in it. Which property of Listbox control should she use to do this?
Ans. Modal property
20. What is constructor? How can you call access super class constructor from sub class.
Ans. Constructor: A member method with the same name as its class is called constructor and it is used to
initialize the objects of that class type with a legal initial value.
By using super keyword we can call access super class constructor from sub class.
21. Ms. Samhita has developed a Java application through which the students of her school can view
their marks by entering their admission number. The marks are displayed in various text fields. What
should she do so that the students are able to view but not change their marks in text fields?
Ans. By uncheck editable property of JTextField.
22. What is the purpose of break statement in a loop?
Ans. The break statement is used to break from an enclosing do, while, for, or switch statement. Break
breaks the loop without executing the rest of the statements in the block.
23. What is the use of super keyword?
Ans. The first use of keyword super is to access the hidden data variables of the super class hidden by
the subclass.
The second use of the keyword super in java is to call super class constructor in the subclass.
24. What are the 3 types of error found in program? Explain them briefly.
Ans.
1. Compile-Time Errors
Compile-time errors (syntax errors and semantics errors) refer to the errors that violate the
grammatical rules and regulations of a programming language.
2. Run-Time Errors
Run-time errors occur during the execution of a program.
CBSE CS N IP
Page 4 of 12
3. Logical Errors
Logical errors occur due to mistaken analysis of the problem.
25. What should be done so that only one of the radio buttons (Male and Female) can be selected at a
time?
Ans. We should use ButtonGroup component so that only one of the radio buttons (Male and Female) can
be selected at a time.
26. A phone number, consisting of 10 digits, is stored in a string variable strPhone. Now it is required to
store this phone number in a Long type variable lngPhone. Write a Java statement to do this.
Ans. String strPhone = "123456789";
long lngPhone = Long.parseLong(strPhone);
System.out.println(lngPhone);
27. Write a java method to fetch the data from the employee table and display it in jTable the method
already having Connection class object name con, Statement class Object name smt and ResultSet
class object rs with the following query
SELECT EMPNO, ENAME, JOB, SAL FROM EMP.
Ans. import java.sql.*;
import javax.swing.table.*;
import javax.swing.JOptionPane.*;
// button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
int rows=model.getRowCount();
if(rows>0)
{
for(int i=0;i<rows;i++)
{
model.removeRow(0);
}
}
String query="select * from emp";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection
con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","");
Statement smt=con.createStatement();
ResultSet rs=smt.executeQuery(query);
while(rs.next())
{
String no=rs.getString("empno");
String name=rs.getString("ename");
String job1=rs.getString("job");
String salary=rs.getString("sal");
CBSE CS N IP
Page 5 of 12
System.out.println(no+"|"+name+"|"+job1+"|"+salary);
model.addRow(new Object[]{no,name,job1,salary});
}
}catch(Exception e)
{ }
}
28. What is abstract method? Write a Java code to demonstrate abstract method.
Ans. An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon). If a class includes abstract methods, the class itself must be declared abstract
Example:
Public abstract class Shape
{
String name;
double area;
public abstract void display();
}
Class Circle extend shape
{
double radius;
double calcArea()
{
return 3.154 * radius * radius;
}
public void display()
{
System.out.println(radius= + radius);
System.out.println(area= + calcArea());
}
}
29. What is Package? Explain various built-in packages of Java.
Ans. Package: A package is a Java language element used to group related classes under a common name.
java.lang: Provides classes that are fundamental to the design of the Java programming
language. The most important classes are Object, which is the root of the class hierarchy, and
Class, instances of which represent classes at run time.
java.util: Contains the collections framework, legacy collection classes, event model, date and
time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a
random-number generator, and a bit array).
30. What is Interface? Write syntax of Interface and implementation of Interface.
Ans. Interface: Interface is similar to a class which may contain methods signature only but not bodies and it
is a formal set of method and constant declarations that must be defined by the class that implements
it.
Syntax of Interface:
interface interface_name {
Interface_body
CBSE CS N IP
Page 6 of 12
}
Syntax of implementation of Interface:
class class_name implements interface_1, interface_2,. {
Interface_body
}
31. Which method converts a string to an integer?
Ans. parseInt()method converts a string to an integer.
32. Write a method in Java that takes two integer arguments and returns power of it. Suppose x and y
passing as an argument then it returns x to power y after calculation.
Ans. int cal_power(int x, int y)
{
int x=Math.pow(x,y);
return(x);
}
33. Write a Method in Java to take a number as argument and print the product of its digit, as if a
number entered is 234 then the program gives o/p as 24.
Ans. import java.io.*;
public class JavaApplication6 {
public static void main(String[] args)
{
int n, r = 0;
int a=1;
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number");
n=Integer.parseInt(br.readLine());
while( n != 0 )
{
r=n%10;
a=a*(r);
n=n/10;
}
System.out.println(" No is=\n "+a);
}catch(Exception e)
{}
}
34. Write the Java Code for Finding Prime No.
Ans. class prime
{
public static void main(String p[])
{
CBSE CS N IP
Page 7 of 12
int i,j,s=0,d=0;
for(i=1;i<100;i++)
{
s=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
s=s+1;
}
if(s==2)
{
System.out.println(i);
d=d+1;
}
}
System.out.println("the no. of prime no. are = "+d);
}
}
35. Write the Java Code for Finding Palindrome Word.
import java.io.*;
class PaliString {
public static void main(String[] args)
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string");
String s=br.readLine();
int i;
int n=s.length();
String str="";
for(i=n-1;i>=0;i--)
str=str+s.charAt(i);
if(str.equals(s))
System.out.println(s+ "is palindrome");
else
System.out.println(s+ "is not a palindrome");
}
catch(Exception e)
{}
}
}
36. Write the Java Code for reverse a given digit.
Ans. import java.io.*;
CBSE CS N IP
Page 8 of 12
Page 9 of 12
}
Write Factorial () function and pass an integer number as a argument and return a factorial of passed
number by using recursion method.
Ans. import java.io.*;
class Factorial
{
long fact(long a)
{
if(a <= 1)
return 1;
else
{
a= a*fact(a-1);
return a;
}
}
public static void main (String arr[])
{
try
{
System.out.println("Enter a number to find factorial");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt( br.readLine());
Factorial f = new Factorial();
System.out.println(f.fact(num));
}catch(Exception e)
{}
}
}
39. Expand the following termsJDBC, API, GUI, JRE, JDK, JVM, IDE
Ans. JDBC: Java DataBase Connectivity
API: Application Programming Interface
GUI: Graphical User Interface
JRE: Java Runtime Environment
JDK: Java Development Kit
JVM: Java Virtual Machine
IDE: integrated development environment
40. Write the purpose of following method with proper example
a. getString()
b. substring()
c. length()
d. capacity()
e. round()
f. isSelected()
38.
CBSE CS N IP
Page 10 of 12
g. getInstance()
h. setSize()
i. getSelectedValue()
j. executeUpdate()
k. getPassword()
l. getSelectedItem()
m. addItem()
n. append()
o. setVisible()
p. createStatement()
q. setEnabled()
r. setEitable()
Ans.
a. getString() : getString() method is provided by ResultSet object and used for obtaining column
data for a row.
Example: String st=rs.getString(ABC);
b. substring(): this method is used to return a part or substring of the String used to invoke the
method. The first argument represents the starting location of the substring.
Example: String s=abcdefghi;
System.out.println(s.substring(5));
System.out.println(s.substring(5,8));
c. length(): This method count and return the number of characters contained in the string object.
Example: String str=Informatics Practices;
System.out.println(str.length());
d. capacity(): Returns the current capacity. The capacity is the amount of storage available for
newly inserted characters, beyond which an allocation will occur.
Example: String str=Informatics Practices;
System.out.println(str. capacity());
e. round() : Rounds to the nearest integer. So, if the value is more than half way towards the
higher integer, the value is rounded up to the next integer.
Example: Math.round(1.01);
f. isSelected(): This is a JCheckBox and JRadioButton method which return the state of the button.
True if the toggle button is selected, false if its not.
Example: if(JRadioButton1.isSelected()==true)
{
JLable1.setText(selected);
}
else
{
JLable1.setText( not selected);
}
g. getInstance(): This method is used to get the instance of a object.
Example: class abc
{
abc ab;
ab.getInstance();
CBSE CS N IP
Page 11 of 12
}
h. setSize(): setSize() is used for setting a size for JFrame.
Example: Jframe1.setSize(100,100);
i. getSelectedValue(): Returns the selected value when only a single item is selected in the list.
When multiple items are selected, it returns the first selected value. Returns null if there is no
selection.
Example: String dur=(String)jList1.getSelectedValue();
jLabel1.setText(dur);
j. executeUpdate(): Execute the given SQL statement, which may be an INSERT, UPDATE or
DELETE statement or SQL statement that returns nothing, such as SQL DDL statement.
Example: String sql=DELETE FROM Employees;
ResultSet rs=stmt. executeUpdate(sql);
k. getPassword():getPassword()method is used to obtain password from a password field.
Example:
String ped=new String(pwdfld.getPassword());
l. getSelectedItem(): Returns the selected item.
Example: String dur=(String)jComboBox1.getSelectedItem();
jLabel1.setText(dur);
m. addItem(): Adds an item to the item list, in the end, of the combo box.
Example: citycb.addItem(ABC);
n. append(): Adds the specified text to the end of the text area.
Example: jTextArea1.append("ABC");
o. setVisible(): Makes the check box visible if true is passed otherwise hides the check box.
Example: jchackBox1.setVisible(true);
p. createStatement(): Creates a SQL statement object for building and submitting an SQL
statement to the database.
Example: Statement stmt = con.createStatement( );
q. setEnabled(): Enables the check box if true is passed otherwise disable the check box.
Example: jchackBox1.setEnabled(true);
r. setEditable(): Sets whether the user can edit the text in the Text Field. Default is true.
Example: NameTF.setEditable(True);
CBSE CS N IP
Page 12 of 12