Showing posts with label Java Beginners Excercises. Show all posts
Showing posts with label Java Beginners Excercises. Show all posts

Saturday, 12 January 2019

Java Beginners Excercises


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");
    }
}

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.
  1. equals(): Case-sensitive check
  2. 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.


Saturday, 30 May 2015

Java Methods

Java methods are equivalent to C++ functions. Objects can communicate with each other using methods. Java’s methods can be classified in the two categories:


  • Instance Methods
  • Static Methods 


Just like static variables and instance variables, there are static methods and instance methods.

1. Instance Methods

The general form of an instance method is:

<return-type> <method-name> (parameter-list)

{

<method-body>

}

Method definition has four parts:


  • Name
  • Return Type
  • List of Parameters
  • Method Body

The return type can be a primitive data type or reference data type. In case, the method returns a 
reference, the return type will be the name of the class to which the object referred to by the returned reference belongs. It is must to declare the return type even if the method does not return any value. In this case, the return type should be declared as void.

The method’s formal parameters/arguments are specified within the parenthesis after the method name. The syntax is same as in C/C++.

The method body may contain any valid Java statement. If the method has a return type, then a value must be returned through return statement.

Invoking/Calling Instance Methods

The dot (.) operator is used to invoke/call the instance methods. The general form for calling the 

instance methods using the dot operator is: 

<object-reference>.<method-name>(paremeter-list)

Where <object-reference> is some reference variable pointing to an object and <method-  name> is the name of an instance method. For example, after creating an object of type Box and storing its reference in the reference variable b1, we can call the instance method  volume() using dot operator as follows: 

Box b1 = new Box();

b1.volume();

Instance methods can access the instance variables as well as static variables.

Example: The following program demonstrates how to call a instance method.

1 class Box 

2 { double width; //instance variables

3 double height;

4 double depth;

5 void volume() //instance method

6 { System.out.println("volume is:" + width * height * depth); 

7 }

8 }

1 class BoxDemo_4

2 { public static void main(String args[])

3   { Box b = new Box();

4 b.width = 10; 

5 b.height = 20;

6 b.depth = 15;

7 b.volume();

8 }

9 }

In the main() method an instance of the class Box is created, its instance variables are initialized and then the instanced method is called. The instance method volume() calculates and displays the volume of the Box.

While accessing an instance variable inside main() method, we have used object reference. It is required, as we can not access an instance variable directly inside a static method. However, when an instance variable is accessed by a method that is defined in the same class as the instance variable, the instance variable can be referred directly. 

In fact we cannot specify the object reference in the method volume(), in the above example. This is due to the fact that unlike instance variables, there is only one copy of the instance methods. The instance methods use the copy of the instance variables of the object through which they are called. So the same method called through different object references will use different copy of the instance variables and hence the name instance method.

Implicitly an instance variable referred directly in a method uses this reference. For example, in the above program the direct reference to variables width, height and length is equivalent to this.width, this.height and this.length. The reference this inside a method refers to the current object (i.e. the object on which the method is called). The reference this is replaced by the reference of the invoking object at run-time. Hence the same instance method invoked through different objects will use different set of instance variables and hence will normally give different results.

Example: The following program demonstrates that calling non-static/instance method on different objects results in different output. 

1 class Box 

2 { double width; //instance variables

3 double height;

4 double depth;

5 void volume() //instance method

6 { System.out.println("volume is "+width*height*depth); 

7 }

8 }

1 class BoxDemo4

2 { public static void main(String args[])

3   { Box b1 = new Box();

4 Box b2 = new Box();

5 b1.width = 10; b1.height = 20; b1.depth = 15;

6 b2.width = 3; b2.height = 6;  b2.depth = 9;
7 b1.volume();

8 b2.volume();

9   }

10 }

The first call to method volume() displays the volume of the box b1 correctly as 6000 and the 
second call to method volume() displays the volume of the box b2 as 162.

Method Returning a value

Example: The following program demonstrates use of method, which returns a value i.e. its 
return type, is not void.

1 class Box 

2 { double width;

3 double height;

4 double depth;

5 double volume()

6 { return width * height * depth; 

7 }

8 }

1 class BoxDemo5

2 { public static void main(String args[])

3   { Box b1 = new Box();

4 Box b2 = new Box();

5 double vol;

6 b1.width = 10;

7 b1.height = 20;

8 b1.depth = 15;

9

10 b2.width = 3;

11 b2.height = 6;

12 b2.depth = 9;

13 vol = b1.volume();

14 System.out.println("Volume is : " + vol);

15 vol = b2.volume();

16 System.out.println("Volume is : " + vol);

17 }

18 }

Passing Arguments to Methods.

In the previous examples using class BoxDemo5, we initialized the instance variables directly to 
keep the things simple. This should not be done as it defeats the purpose of data encapsulation.

Moreover the instance variables can be made private so that they cannot be accessed from other 
classes. In that case it would not be possible to access the instance variables directly. The only 
alternative in that case is to define a method that takes width, height, and length as arguments 
and then initializes the instance variables.

Example: The following program defines two classes: Box and BoxDemo6. The class Box has a 
method that takes arguments. The classes may be defined in same source file or in two different 
source files. But in both the cases you will get two classes after compilation: Box.class and 

BoxDemo6.class. You can execute only class BoxDemo6.class as only this class has main() 
method. It also makes use of class Box for creating an instance/object and calling methods.

1. class Box

2. { private double width, height, depth; //data hiding

3. double volume()

4. { double vol = width * height * depth;

5. return vol;

6. }

7. void setDimensions(double w, double h, double d)

8. { width = w;

9. height = h;

10. depth = d; 

11. }

12. /* Instance Variable Hiding 

13. void setDimensions(double width,double height,double depth)

14. { width = width;

15. height = height;

16. depth = depth; 

17. }

18. */

19. /* Instance Variable Hiding 

20. void setDimensions(double width,double height,double depth)

21. { this.width = width;

22. this.height = height;

23. this.depth = depth; 

24. }

25. */

26. }

1 class BoxDemo6

2 { public static void main(String args[])

3    { Box b1 = new Box();

4 Box b2 = new Box();

5 b1.setDimensions(10, 20, 30);

6 double volume = b1.volume();

7 System.out.println(volume);

8 b2.setDimensions(5, 10, 15);

9 volume = b2.volume();

10 System.out.println(volume);

11 }

12 }

You cannot access the instance variables of class Box though object reference in the class 
BoxDemo6 as instance variables are declared private. The private instance variables can be 
accessed only in the class in which they are declared.

Nesting of Instance Methods

One instance method can invoke the other instance method of the same class without qualifying 
i.e. by just specifying the method name. For example, in the following program, calCost() 
method, which is an instance method, can call the instance method area() of the same class 
simply by its name.

1 class Circle

2 { static final float  PI = 3.1415f;

3 float puCost; // say cost of painting unit area

4 float radius;

5 float area()

6 { return PI * radius * radius;

7 }

8 float calCost()

9 {

10 float cost = puCost * area();

11 return cost;

12 }

13 public static void main(String args[])

14 { Circle circle = new Circle();

15 circle.puCost = 100;

16 circle.radius = 3;

17 float area = circle.calCost();

18 System.out.println(area); 

19 }

20 }

2. static Methods 

The static methods can be accessed like static variables through the class name without creating 
any instance/object. The static methods can also be called using the object reference. The static 
methods can directly access only static variables irrespective of the fact that they are invoked 
through class name or object reference.

The general form of a static method is:

static <return-type> <method-name> (parameter-list)


<method-body>


The general form is same as that of a instance method with the only difference that the modifier 
static is used before the return type.

Invoking/Calling static Methods

Example: The following program demonstrates the use of static method. The method area() 
takes one argument representing the radius of the circle and calculates its area. The method area() does not use any instance variable so it is declared as static and can be invoked through class name without creating any instance/object.

1 class Circle

2 { static final float  PI = 3.1415f;

3 static float area(float radius)

4 { return PI * radius * radius;

5 }

6 public static void main(String args[])

7 { int r = 4;

8 float area = Circle.area(r); 

9 //float area = area(r); //Nesting of static methods 

10 System.out.println("Area: "+area); 

11 }

12 }

Here the static variable PI is declared to be constant by putting modifier before the type. This is 
equivalent to const of C/C++.

Nesting of Class Methods

One class method can invoke the other class method of the same class without qualifying i.e. by 
just specifying the method name. For example, in the above program main() method, which is 
static can call the static method area() of the same class simply by its name: 

float area = area(r);

This nesting can go to any depth.