Que 1: Answer the below questions based on the following Java program:
public class
MyFirstProgram {
public static void main(String[] args){
System.out.println("hello world");
}
}
public static void main(String[] args){
System.out.println("hello world");
}
}
A; What would
be the Java file name for the above Java program and why?
Ans: The file name will be MyFirstProgram.java. The file name should be the same as the
name of the public class defined.
B: What is
the command used to compile and run the above Java program. Write the
full command.
Ans: Compile: javac
MyFirstProgram.java, Run: java MyFirstProgram
Que 2: How
many data types are available in Java?
Ans:
Integer: int, short,
long, byte
Floating point:
float, double
Char type: char
Boolean type:
boolean
Que 3: How
can we define variables in Java? Please provide an example.
Ans:
public class
DefineSomeVariables
{
double salary;
int
vacationDays = 12;
long
earthPopulation
boolean done;
}
Que 4: How
can we define constants in Java? Please provide an example.
Ans: We use the
keyword final to denote a constant.
public class
Constants
{
public static
void main(String[] args)
{
final
double CM_PER_INCH = 2.54;
final
INCH = 12;
}
}
Que 5: Which
In-built class does Java provide for mathematical operations. Please
provide some basic examples using that class.
Ans: Java provide
Math class.
Below are some
examples:
1: To take the
square root of a number, use the sqrt method:
double x = 4;
double y =
Math.sqrt(x);
System.out.println(y);
// prints 2.0
2: The Math class
supplies the usual trigonometric functions:
Math.sin
Math.cos
Math.tan
Math.atan
Math.atan2
Que 6: What
is the data type conversion in Java? Please explain using an example.
Ans: When we
assign the 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 cast or converted
explicitly.
For example:
The syntax for
casting is to give the target type in parentheses, followed by the
variable name.
double x = 9.997;
int nx = (int) x;
Now, the variable nx
has the value 9 because casting a floating-point value to an integer
discards the fractional part.
Que 7:
Explain operator combining in Java using an example.
Ans:
x += 4;
is equivalent to
x = x + 4;
(In general, place
the operator to the left of the = sign, such as *= or %= .)
If the operator
yields a value whose type is different than that of the left-
hand side, then it
is coerced to fit. For example, if x is an int , then the statement
x += 3.5;
is valid, setting x
to (int)(x + 3.5) .
Que 8: Is
Java supports Increment and Decrement Operators? If yes then explain
using an example.
Ans: Yes java
supports both Increment and Decrement Operators.
Example:
int n = 12;
n++;
changes n to 13.
Since these operators change the value of a variable, they cannot
be applied to
numbers themselves. For example, 4++ is not a legal statement.
int a = 2 * ++m; //
now a is 16, m is 8
int b = 2 * n++; //
now b is 14, n is 8
The same way we can do
--n and n--.
Que 9: What
are the relational operators in Java? Provide some examples.
Ans: Java has
six relational operators that compare two numbers and return a
boolean value. The relational operators are <, >, <=, >=,
==, and !=.
Examples:
x < y |
Less than |
True if x is less than y, otherwise false. |
x > y |
Greater than |
True if x is greater than y, otherwise false. |
x <= y |
Less than or equal to |
True if x is less than or equal to y, otherwise false. |
x >= y |
Greater than or equal to |
True if x is greater than or equal to y, otherwise false. |
x == y |
Equal |
True if x equals y, otherwise false. |
x != y |
Not Equal |
True if x is not equal to y, otherwise false. |
Que 10: What
are Enumerated types in Java? Explain using an example.
Ans: Sometimes,
a variable should only hold a restricted set of values.
For example:
you may sell clothes
or pizza in four sizes: small, medium, large, and extra large.
Of course, you could
encode these sizes as integers 1, 2, 3, 4 or characters S, M, L,
and X . But that is
an error-prone setup. It is too easy for a variable to hold a wrong
value (such as 0 or
m ).
We can define our
own enumerated type whenever such a situation arises. An
enumerated type has
a finite number of named values. For example:
enum Size { SMALL,
MEDIUM, LARGE, EXTRA_LARGE };
Now we can declare
variables of this type:
Size s =
Size.MEDIUM;
A variable of type
Size can hold only one of the values listed in the type declaration,
or the special value
null indicates that the variable is not set to any value at all.
Que 11: Is
there any data type for Strings in Java? Please explain the basic concept
of String in Java?
Ans: No, Java
does not support any data type for Strings. The standard Java library
contains a predefined class called String.
Example:
Each quoted string
is an instance of the String class:
String e = "";
// an empty string
String greeting =
"Hello";
Que 12: Write
a program to print the first three letters from a given string.
Hint: Use the substring
method of the String class.
Ans:
public class
SubstringExample{
public static
void main(String args[]){
String
greeting = "Hello";
String s
= greeting.substring(0, 3);
System.out.println(“First
three letters of given String: ” + s);
}
}
Que 13: What
methods String class provides to test equality between two strings?
Please provide an example.
Ans: String
class provides the following two methods to test the equality which
returns true or false.
- equals(): Case-sensitive check
- equalsIgnoreCase(): Case insensitive
Examples:
1. String greeting =
"Hello";
"Hello".equals(greeting); // returns true
2. String greeting =
"hello";
"Hello".equals(greeting); // returns false
"Hello".equalsIgnoreCase(greeting) // returns true
Que 14: What
is the significance of NULL and Empty String? Please explain using
appropriate examples.
Ans:
Empty: The
empty string "" is a string of length 0. We can test
whether a string is empty
by calling
if (str.length() ==
0)
or
if (str.equals(""))
An empty string is a
Java object which holds the string length (namely 0 ) and an
empty contents.
NULL: a
String variable can also hold a special value, called null, that
indicates that no object is currently associated with the variable.
To test whether a
string is null, use the condition
if (str == null)
Sometimes, we need
to test that a string is neither null nor empty. Then use the
Condition
if (str != null &&
str.length() != 0)
We need to test that
str is not null first. It is an error to invoke a method on a null
value.
Que 15: Write
down some mostly used String class method names.
Ans:
char charAt(int
index)
boolean
startsWith(String prefix)
boolean
endsWith(String suffix)
int indexOf(String
str)
int
lastIndexOf(String str)
String
replace(CharSequence oldString, CharSequence newString)
String substring(int
beginIndex)
String substring(int
beginIndex, int endIndex)
String toLowerCase()
String toUpperCase()
String trim()
boolean
equals(Object other)
boolean
equalsIgnoreCase(String other)
Que 16: What
is the use of the Scanner class? Explain using an example.
Ans: Scanner
class is used to read input from the command line.
Example:
public class
CommandLineInput
{
public static
void main(String args[])
{
Scanner in
= new Scanner(System.in);
System.out.print("What is your name? ");
String name
= in.nextLine();
System.out.print("Your name is: "+name);
//Get
second input
System.out.print("How old are you? ");
int age =
in.nextInt();
System.out.print("Your age is: "+age);
}
}
Que 17: Explain
the IF conditional statement using an example.
Ans:
The conditional
statement in Java has the form
if (condition)
statement
The condition must
be surrounded by parentheses.
Example:
if (yourSales >=
target)
{
performance =
"Satisfactory";
bonus = 100;
}
Que 18: Explain
FOR and WHILE loop.
Ans:
While Loop: The
while loop executes a statement (which may be a block statement)
while a
condition is true.
The general form is
while (condition)
statement
The while loop will
never execute if the condition is false.
Example:
while (balance <
goal)
{
balance +=
payment;
double interest
= balance * interestRate / 100;
balance +=
interest;
years++;
}
For loop: The
for loop is a general construct to support iteration controlled by a
counter or
the similar variable
that is updated after every iteration.
Example: the
following loop prints the numbers from 1 to 10 on the screen.
for (int i = 1; i <=
10; i++)
System.out.println(i);
Que 19: What
is the Array? How do we declare and initialize arrays in Java? Explain
using an example.
An array is a data
structure that stores a collection of values of the same type.
We access each
individual value through an integer index.
For example, if a is
an array of integers, then a[i] is the i th integer in the array.
Array
Declaration:
int[] a; // array a
of integers
Array
Initialization:
int[] a = new
int[100]; // This statement declares and initializes an array of 100
integers.
Que 20: Create
a method to insert and print elements from an array.
Ans:
public void
arrayExample()
{
// Initialize
the array
int[] a = new
int[10];
// Get the
array length by using length property
int length =
a.length;
// Insert
values in the array
for (int i = 0;
i < a.length; i++)
a[i] =
i+10;
//Print the
array
for (int i = 0; i
< a.length; i++)
System.out.println(a[i]);
}
Que 21: What
is the class in Java? Generally what things we can have inside a
class?
Ans: A class
is a template or blueprint from which objects are made. Think about
classes as cookie
cutters. Objects are the cookies themselves. When you construct
an object from a
class, you are said to have created an instance of the class.
Generally, a class
have fields/variables and methods. All code that we write in Java
is inside a class.
Que 22: In
OOPs what are the main characteristics of objects?
Ans:
- The object’s behaviour—what can you do with this object, or what methods can
you apply to it?
- The object’s state—how does the object react when you invoke those methods?
- The object’s identity—how is the object distinguished from others that may
have the same behaviour and state?
Que 23: What
are the differences between the Procedural program and OOP?
Ans:
In a traditional
procedural program, we start the process at the top, with the main
function. When
designing an object-oriented system, there is no “top,” and new-
comers to OOP often
wonder where to begin. The answer is: Identify your classes
and then add methods
to each class.
in an
order-processing system, some of the nouns are
Item
Order
Shipping address
Payment
Account
These nouns may lead
to the classes Item, Order, and so on.
Que 24: What
are the Constructors in Java?
Ans:
In the Java
programming language, we use constructors to construct new instances.
A constructor is a
special method whose purpose is to construct and initialize
Objects.
Constructors always
have the same name as the class name. Thus, the constructor
for the Date class
is called Date. To construct a Date object, combine the constructor
with the new
operator, as follows:
new Date()
This expression
constructs a new object. The object is initialized to the current
date and time.
Que 25: Write
5 properties/characteristics of Constructors.
Ans:
- A constructor has the same name as the class.
- A class can have more than one constructor.
- A constructor can take zero, one, or more parameters.
- A constructor has no return value.
- A constructor is always called with the new operator.
Que 26: What
happens when we defile class fields as static?
Ans:
If we define a field
as static, then there is only one such field per class. In contrast,
each object has its
own copy of all instance fields. For example, let’s suppose we
want to assign a
unique identification number to each employee. We add an
instance field id
and a static field nextId to the Employee class:
class Employee
{
private static int nextId = 1;
private int id;
. . .
}
Every employee
object now has its own id field, but there is only one nextId field
that is shared among
all instances of the class. Let’s put it another way. If there
are 1,000 objects of
the Employee class, then there are 1,000 instance fields id, one for
each object. But
there is a single static field nextId . Even if there are no employee
objects, the static
field nextId is present. It belongs to the class, not to any
individual
object.
Que 27: What
are the Static Methods in Java?
Ans:
Static methods are
methods that do not operate on objects. For example, the pow method
of the Math class is a static method.
The expression
Math.pow(x, a) computes the power x a. It does not use any Math
object to carry out its task.
In other words, it
has no implicit parameter.
We can think of
static methods as methods that don’t have this parameter.
Here is an example
of such a static method:
public static int
getNextId()
{
return nextId; // returns static field
}
To call this method,
we supply the name of the class:
int n =
Employee.getNextId();
Que 28: What
is Overloading?
Ans: some
classes have more than one constructor.
For example, you can
construct an empty StringBuilder object as
StringBuilder
messages = new StringBuilder();
Alternatively, you
can specify an initial string:
StringBuilder
todoList = new StringBuilder("To do:\n");
This capability is
called overloading. Overloading occurs if several methods have the
same name (in this case, the StringBuilder constructor method) but
different parameters.
The compiler must
sort out which method to call. It picks the correct method by
matching the parameter types in the headers of the various methods
with the types of values used in the specific method call.
A compile-time error
occurs if the compiler cannot match the parameters, either because
there is no match at all or because there is not one that is
better than all others.
Que 29: How
can we call one constructor from another?
Ans:
The keyword this
refers to the implicit parameter of a method. However, this keyword
has a second meaning.
If the first
statement of a constructor has the form this(. . .) , then the
constructor calls another constructor of the same class.
Here is a typical
example:
public
Employee(double s)
{
// calls Employee(String, double)
this("Employee #" + nextId, s);
nextId++;
}
When you call a new
Employee(60000), the Employee(double) constructor calls the
Employee(String, double) constructor.
Using this
keyword in this manner is useful—you only need to write common
construction code
once.
Que 30: What
are the Initialization Blocks? Explain using an example.
Ans:
Class declarations
can contain arbitrary blocks of code. These blocks are executed
whenever an object of that class is constructed. For example:
class Employee
{
private static int nextId;
private int id;
private String name;
private double salary;
// object initialization block
{
id = nextId;
nextId++;
}
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee()
{
name = "";
salary = 0;
}
. . .
}
In this example, the
id field is initialized in the object initialization block, no matter
which constructor is used to construct an object. The initialization
block runs first, and then the body of the constructor is executed.
No comments:
Post a Comment