Header Ads Widget

Java Programming (3350703) Assignment -2

 


_Java Programming

(3350703) 

Assignment -2 


1. Explain Primitive data types in java.

answer:- 

There are eight type of primitive data types.

byte:- 

it is a signed data type of size 8 bits.

It has a range from -128 to 127.

This is smallest integer type.

short:-

short is a signed data type of size 16 bits.

It has range from -32,768 to 32,767.

int:-

int is a signed data type of size 32 bits.

it has a range from -2147483648 to 2147483647.

long:-

long is a signed data type of size 64 bits.

It has a range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

float:-

it is 32 bits in size.

float specifies a single-precision value.

It has a range from 1.4e+045 to 3.4e+038. 

example :- float f1=12.3434f;

double:-

it is 64 bit in size.

example :- double d1= 212.3232;

char:-

In Java, the data type used to store characters is char.

char data type is of size 16 bits.

The range of char is 0 to 65536.

boolean:-

boolean is an of size 1 bit.

boolean is a simple type, called, for logical values.

it has only two possible values true and false.

 

2. Explain User defined data types in java. 

answer:- 

User defined data types are arrays, classes and interfaces.

Array type:-

In Java, array is a user defined data type because it implicitly extends java. lang.Object.

An array contains value called elements.

Array allows the user to store the values of the same type in contiguous memory allocations.

All elements of an array must contain same type of value.

Class type:-

Java is an object-oriented programming language, where the class is treated as a type in java program.  

Interface type:-

In order to support multiple inheritance feature in java, we have an of reference data type or mechanism called interface.


3. Explain different types of literals in java. 

answer:- 

It's a value of a variable such as 123, -456, 3-14, 'a', "Hello", it can be of any Java data types.

Literals provide a means of expressing specific values in your program

~Boolean Literals

~Character Literals

~Integer Literals

~Floating Point Literals

~String Literals

~null Literals



4. Explain constant in java. 

answer:- 

Constants are declared with keyword final.

Their values cannot be changed during execution.

For example :

final double PI = 3.1415926;


5. Explain scope of variables in Java. 

answer:- 

The scope of a variable defines the section of the code in which the variable is visible.

you can declare variable in several different places:

A member variable is a member of a class or an object. A member variable's scope is the entire declaration of the class.

The local variable is declared within a block of code. In general, the scope of a local variable is the block in which it was declared.

Parameters are used to pass value into methods. The scope of a parameter is the entire method.

Exception-handler parameter are arguments to an exception handler. Its scope is the code block between { and } that follows a catch statement. 


6. What is type conversion & casting? 

answer:- 

There are two type of Type-Conversion in Java:

1)Implicit type-conversion

2)Explicit type-casting

Implicit Type conversion:-

Implicit type-conversion is performed by compiler automatically. 

There is no loss of precision. 

For example

int=3;
double=f;
f=i; 

Explicit type-casting:-

Type-casting forces an explicit conversion of the type of a value.

Type-Casting is an operation which takes one operand, it operates on its operand, and returns an equivalent value in the specified type.

Syntax:-   newvalue=(typecast)value; 


7. Describe JAVA selection statement with example. 

answer:- 

Selection statements allows the program to choose different paths of execution based upon the outcome of an conditional expression or the state of a variable.

There are two Selection statement in Java. if and switch

The if else Statement:-

Syntax:-

 if(Boolean_expression)
{
       //execute if the boolean expression is true
}
 else
{
       //execute if the boolean expression is false
}

The Switch Statement:-

Syntax:-

switch(expression)
{
    case value:
        //statements
        break;

    case value:
        //statements
        break;
   default:
          //statements
}

8. List the types of operators available in Java. Explain arithmetic and Bitwise operators. 

answer:- 

The types of Operator is given below:

Unary

Arithmetic

Shift

Relational

Bitwise

Logical

Ternary

Assignment

Arithmetic :- Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.

The arithmetic operator are  

(+) addition

(-) Subtraction

(*) Multiplication

(/) Division

(%) Modulus 

(++) Increment

(--)Decrement

Bitwise:- Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and perform bit by bit operation.

The Bitwise operators are :

(&) AND

( | ) OR

(^) XOR

(~) bitwise compliment

(<<) left shift

(>>) right shift 

(>>>) zero fill right shift


9. Give difference between string and string buffer class, explain any three methods of both string & string buffer class. 

answer:- 

string:-

String class is immutable string object.
String is slow and consumes more memory 
String class is used to create string object.

string buffer class:-

String Buffer  class is mutable string object.
String Buffer  is fast and consumes less memory.
String class is used to create mutable string object.


String methods:-
Length():- 
This method is used to get the length of a string:
Example:-
    char Name[ ]={'H','E','L'.'L'.'O'};
    string strName = new String(Name);
    System.out.println(strName.length()); 

charAt():-
This method returns the character at a specific index in string.
Syntax :--  char charAt(int index)


getChars():-
To extract more than one characters from a string.
Syntax:-
void getChars (int start, int end, char target[], int tstart);


String Buffer methods:-

replace():- 
This method replaces the string from specified start index to the end index.

Capacity():- 
This method returns the current capacity of StringBuffer object.

reverse():- 
This method reverse the characters within a StringBuffer object. 

10. What is wrapper class? Explain all conversion which occurs with wrapper class. 

answer:- 

The class which "wrap" the primitive data type into an object of that class is called as Wrapper Class.

we can not use the primitive data type as objects directly so we use wrapper class to wrap the primitive  data types into objects.

booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble


11. Explain any four string function in JAVA with example. 

answer:- 

Length():- 
This method is used to get the length of a string:
Example:-
    char Name[ ]={'H','E','L'.'L'.'O'};
    string strName = new String(Name);
    System.out.println(strName.length()); 

replace():- 
This method replaces the string from specified start index to the end index.
Example:-
StringBuffer str = new StringBuffer("Hello World");
str.replace(6, 11, "java:);
System.out.println(str);


charAt():-
This method returns the character at a specific index in string.
Syntax :--  char charAt(int index)
Example:-
{
    String s="Indian";
    System.out.println(s.charAt(0));
    System.out.println(s.charAt(3));
}



concat():- Appends a string to the end of another string.
Example:- 
string s = "Hello";
string str = "Java";
string str2 = s.concat(str);
String str1 = "Hello".concat("Java");


12. List seven method of string class. Explain all of them with examples. 

answer:- 

Length():- 
This method is used to get the length of a string:
Example:-
    char Name[ ]={'H','E','L'.'L'.'O'};
    string strName = new String(Name);
    System.out.println(strName.length()); 

replace():- 
This method replaces the string from specified start index to the end index.
Example:-
StringBuffer str = new StringBuffer("Hello World");
str.replace(6, 11, "java:);
System.out.println(str);


charAt():-
This method returns the character at a specific index in string.
Syntax :--  char charAt(int index)
Example:-
{
    String s="Indian";
    System.out.println(s.charAt(0));
    System.out.println(s.charAt(3));
}



concat():- Appends a string to the end of another string.
Example:- 
string s = "Hello";
string str = "Java";
string str2 = s.concat(str);
String str1 = "Hello".concat("Java");


copyValueOf():- Returns a String that represents the characters of the character array.
Example:-
 str1 = str1.copyValueOf(data);
      System.out.println("str1 after copy: " + str1);


Capacity():- 
This method returns the current capacity of StringBuffer object.
Example:-
StringBuffer str = new StringBuffer();
System.out.println(str.capacity());

reverse():- 
This method reverse the characters within a StringBuffer object. 
Example:-
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);

//olleh

13. Explain Garbage Collection and finalize() method. 

answer:- 

Garbage collection is a process of reclaiming the runtime unused memory automatically.

In other words, it is a way to destroy unused objects.

In Java, the programmer need not to care for objects which are no longer in use.

Garbage collector destroy these objects, but it is not guaranteed that it run at any specific time, it runs on low priority.

Finalize() method:- 

The finalize method is invoked each time before the object is garbage collected.

This method can be used to perform cleanup processing.

This method is defined in object Class as: protected void finalize(){} 



14. List and explain types of array (Rectangular and Non Rectangular type) with example. 

answer:- 

There are two types of array 1) single dimensional array 2)multidimensional array

Rectangular array:-

Rectangular arrays are, as the name implies, arrays which look like a table. A 2D rectangular array can be represented as a plane rectangle, and a 3D rectangular array can be represented as a cuboid. [4] Whatever the case, the idea is the same – in rectangular arrays, every row has the same number of columns

public class TwoDimArrayDemo
{
public static void main (String []args)
    {
int twoDim [][]=new int [2][3];
twoDIm=[0][0]=1;
twoDIm=[0][1]=2;
twoDIm=[0][2]=3;
twoDIm=[1][0]=4;
twoDIm=[1][1]=5;
twoDIm=[1][2]=6;
System.out.println(twoDim[0][0] + " " + twoDim[0][1]+ " " + twoDim[0][2]);
System.out.println(twoDim[1][0] + " " + twoDim[1][1]+ " " + twoDim[1][2]);
    }

}


Non-Rectangular Array:- A nonrectangular array is an array in which each row of the array may have a different number of columns.

class Main {
    public static void main(String[] args)
    {
        int arr[][] = new int[2][];
        arr[0] = new int[3];
        arr[1] = new int[2];
        int count = 0;
        for (int i = 0i < arr.lengthi++)
            for (int j = 0j < arr[i].lengthj++)
                arr[i][j] = count++;

        System.out.println("Contents of 2D Jagged Array");
        for (int i = 0i < arr.lengthi++) {
            for (int j = 0j < arr[i].lengthj++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}





15. Distinguish between break and continue statements in Java. 

answer:- 

Break:- 

The break statement is used to terminate the loop.
we can use break with switch statement.
It stops the execution of loop.

Continue:-

The continue statement is used to skip the current iteration.
we cannot use continue with switch statement. 
It does not stop the execution of the loop.

16. Write a program to sort an array of five Strings. 

answer:- 

import java.util.Arrays;
 
public class SortExample
{
    public static void main(String[] args)
    {
        // Our arr contains 8 elements
        int[] arr = {13, 7, 6, 45, 21};
 
        Arrays.sort(arr);
 
        System.out.printf("Modified arr[] : %s",
                          Arrays.toString(arr));
    }
}


17. Write a Java Program to sort array of 5 integer numbers in ascending order.  

answer:- 

public class SortAsc 
{    
    public static void main(String[] args)
     {      
        int [] arr = new int [] {52871};     
        int temp = 0;    
        System.out.println("Elements of original array: ");    
        for (int i = 0i < arr.lengthi++)
          {     
             System.out.print(arr[i] + " ");    
         }     
        for (int i = 0i < arr.lengthi++) 
            {     
            for (int j = i+1j < arr.lengthj++) 
               {     
               if(arr[i] > arr[j]) 
                    {    
                   temp = arr[i];    
                   arr[i] = arr[j];    
                   arr[j] = temp;    
                    }     
              }     
         }    
        System.out.println();      
        System.out.println("Elements of array sorted in ascending order: ");    
        for (int i = 0i < arr.lengthi++) {     
            System.out.print(arr[i] + " ");    
        }    
    }    
}    






Post a Comment

1 Comments

  1. This was a very meaningful post, so informative and encouraging information, Thank you for this post.
    Washing machine repairing services in Rawalpindi

    ReplyDelete