Tuesday, December 27, 2011
Birlasoft previous question papers free download
Baan previous question papers free download
Aztec previous question papers free download
Alayance previous question papers free download
Accenture previous question papers and interview questions free download
Head first servlets and jsp pdf ebook free download
Core Servlets and Java Server Pages java ebook free download
Saturday, December 24, 2011
Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiguity for the compiler.
What is a "stateless" protocol ?
HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.
What is the concept of a Virtual Function in java?
A virtual function is a function member of a class, declared using the "virtual" keyword. Virtual function can be used to override the properties of a function.it is normally used in inheritance. it is part of polymorphism.
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
What is Downcasting in java?
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy. (or) The process of converting higher data type into lower is known as down casting.
What are the four corner stones of OOP ?
1.Abstraction : Hiding Unnecessary part of data in the program is called abstraction.
2.Inheritance: It is the process of deriving a new class from old one. The old class is known as super class and the new one is sub class
3.Polymorphism: Ability to take more than one form is called polymorphism. Method overloading and overriding are the examples of polymorphism.
4.Encapsulation: Wrapping up of methods and variables into a single unit is called encapsulation.
What is the Difference between a Class and an Object in java?
Object: It is a basic run time entity. (or) Object is an instance of a class. Object consists of state and related behavior.An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages).
Class: Collection of objects under one roof is generally treated as a class. (or) It is a blueprint for an object.
What do you understand by private, protected and public ?
These are accessibility modifiers.
private:
Private is the most restrictive. Private variables and methods can be accessed with in the class only. We can not access private variables and methods outside the class.
public:
Public is the least restrictive. Public classes can be accessed with in the package and outside the package also.
protected:
It is available to the all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default:
It is available to the all classes in the same package.
private:
Private is the most restrictive. Private variables and methods can be accessed with in the class only. We can not access private variables and methods outside the class.
public:
Public is the least restrictive. Public classes can be accessed with in the package and outside the package also.
protected:
It is available to the all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default:
It is available to the all classes in the same package.
Friday, December 23, 2011
How To Implement a Singleton class in java?
Singleton class: Singleton is a class which has only one instance throughout the application. So that it does not allow to create more than one instance.
How to implement singleton class:
Creating and implementing a singleton class is very simple. To implement singleton class, first we make the constructor as private. So that we can not create an object outside the class. We declare an object as static. Later we create one static method. So that before creating an object, we can call this method by using class name. In this method we create an object of a class.Consider the follwoing example that illustrates how to create a singleton class.
Example:
class singletonexample
{
private static singletonexample obj;
private singletonexample()
{
}
public static example()
{
if(obj==null) //it will be true only if the object is not created before
obj=new singletonexample();
}
}
class demo
{
public static void main(String args[])
{
singletonexample.example(); //with class name we call static method
}
}
In the above example, constructor is declared as private. So that we can not create an object outside the class. We declared one static method. So that we can call this method before creating an object of a class. If(obj==null) , it verifies whether the object is already created or not. If the object is not created before, it will return true.
How to implement singleton class:
Creating and implementing a singleton class is very simple. To implement singleton class, first we make the constructor as private. So that we can not create an object outside the class. We declare an object as static. Later we create one static method. So that before creating an object, we can call this method by using class name. In this method we create an object of a class.Consider the follwoing example that illustrates how to create a singleton class.
Example:
class singletonexample
{
private static singletonexample obj;
private singletonexample()
{
}
public static example()
{
if(obj==null) //it will be true only if the object is not created before
obj=new singletonexample();
}
}
class demo
{
public static void main(String args[])
{
singletonexample.example(); //with class name we call static method
}
}
In the above example, constructor is declared as private. So that we can not create an object outside the class. We declared one static method. So that we can call this method before creating an object of a class. If(obj==null) , it verifies whether the object is already created or not. If the object is not created before, it will return true.
Wednesday, December 14, 2011
What are the two types of multi-tasking?
Multi-tasking:
In multi-tasking several tasks are given to the processor at a time. Suppose there are 4 tasks that we want to execute. The microprocessor has to execute them all at a time. So processor will take some time duration, like a milli second and divides the time between number of jobs. So 4 jobs are there. So we get 1/4 millisecond time for each job. First it will execute first job. If it is completed with in the time it goes for 2nd job. Otherwise it will store the results in temporary memory. After executing the 4th job again it comes for 1st job. This will be done in a circular manner. This is called round robin method.
multi-tasking is of two types.
1.Process based multi-tasking
2.Thread based multi-tasking
1.Process based multi-tasking:
Multiple processes are given to the processor at a time.
2.Thread based multi-tasking:
Several parts of the same program is executed at a time. If the program contains two parts, it will use two threads.
What is the difference between preemptive scheduling and time slicing?
Preemptive scheduling means, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Tuesday, December 13, 2011
what is the difference between && and & in java ?
Difference between && and &:
1. Single & can be used as both bitwise operator and logical operator. But && can be used as only logical operator.
2. When we use double && between two expressions, if first expression returns false, second expression will not be evaluated. When we use single & between two expressions, Both expressions will be evaluated even first expression is false.
Example:
Using Single &:
int i=6;
if(i<4 & i++<10)
{
//some code
}
here
first expression: i<4
second expression: i++<10
In the above example, first expression is false. Because i value is 6. But second expression is also evaluated so now i value is 7.
Using &&:
int i=6;
if(i<4 && i++<10)
{
//some code
}
here
first expression: i<4
second expression: i++<10
In the above example, first expression is false. Because i value is 6. But second expression will not be evaluated.
What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
What is a static method?
Static Method:
1. Static method is a method,that do not act on objects. Means we can call a static method before creating an object of a class by using class name.
2. Static methods are executed first in the program. Due to this reason only, we use static before main() method. So that main is called before creating an object.
3.You can define as many static methods as you want in a .java file. These methods are independent, except that they may refer to each other through calls. They can appear in any order in the file.
4. Static methods will accept only static variables,these variables should be declared outside the static method.
5. If a variable is declared as static, then it is initialized only once,even if you call n number of times of that class or function.
6. Static variables are destroyed before termination of the main() method.
What is the difference between method overloading and overriding?
Difference between method overloading and overriding:
Method overloading:
1. If the same method name is used with different arguments, then it is called method overloading.
Ex:
void sum(int x,int y)
void sum(int x,int y,int z)
2. Method overloading will be done with in the same class.
3. Method overloading is an example of static polymorphism.
Method overriding:
1.If the we define the same method name in the super class and sub class, then sub class method will override the super class method. This is called method overriding.
2. Method overriding is done only when there is a super and sub class.
3.Method overriding is an example of run time polymorphism.
What are the differences between abstract class and interface?
Differences between abstract class and interface:
Abstract class:
1. Abstract class is also like a class but contains abstract methods(A method without body) as well as normal methods.
2. To declare abstract methods in abstract class, we should use abstract keyword.
3. An abstract class can not support multiple inheritance.
4. To implement an abstract class we use extends keyword.
Interface:
1.Interface is also like a class but contains only abstract methods.
2.To declare abstract methods in interface, you need not use abstract keyword.
3. Multiple inheritance is possible with interfaces, we can implement as many interface as we need.
4. To implement an interface we use implements keyword.
Abstract class:
1. Abstract class is also like a class but contains abstract methods(A method without body) as well as normal methods.
2. To declare abstract methods in abstract class, we should use abstract keyword.
3. An abstract class can not support multiple inheritance.
4. To implement an abstract class we use extends keyword.
Interface:
1.Interface is also like a class but contains only abstract methods.
2.To declare abstract methods in interface, you need not use abstract keyword.
3. Multiple inheritance is possible with interfaces, we can implement as many interface as we need.
4. To implement an interface we use implements keyword.
How is final different from finally and finalize()?
final is a modifier which can be applied to a class or a method or a variable. If a class is declared as final, it can't be inherited, If a method is declared as final, it can't be overridden and if a variable is declared as final , it can't be changed.
finally keyword is used in exception handling mechanism. It will be executed after completion of try/catch block. The main difference between catch and finally is, catch() block will be executed only if there is any exception in try block. But finally block is executed even there is no exception.
finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.
finally keyword is used in exception handling mechanism. It will be executed after completion of try/catch block. The main difference between catch and finally is, catch() block will be executed only if there is any exception in try block. But finally block is executed even there is no exception.
finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.
Can a class be declared as static?
No a class cannot be defined as static. Only a method, a variable or a block of code can be declared as static.
What is the use of final keyword?
final keyword: If a variable is declared as final, it's value can not be changed. If we try to change the value of a variable which is declared as final, it gives error.
Example:
final int MAX=0;
MAX++; //error.
Another use of final keyword: If a method is declared as final it can not be overridden. So to prevent method overriding we can use final keyword.
Example:
class A
{
void show()
{
System.out.println("Base Class");
}
}
class B extends A
{
void show() //Error, it can not be overridden
{
System.out.println("Sub Class") ;
}
}
Another use of final: If a class is declared as final, it can not be inherited. So to prevent inheritance we can use final keyword.
Example:
final class A
{
}
class B extends A //Error,it can not be inherited
{
}
Example:
final int MAX=0;
MAX++; //error.
Another use of final keyword: If a method is declared as final it can not be overridden. So to prevent method overriding we can use final keyword.
Example:
class A
{
void show()
{
System.out.println("Base Class");
}
}
class B extends A
{
void show() //Error, it can not be overridden
{
System.out.println("Sub Class") ;
}
}
Another use of final: If a class is declared as final, it can not be inherited. So to prevent inheritance we can use final keyword.
Example:
final class A
{
}
class B extends A //Error,it can not be inherited
{
}
Prime Number Program In Java
import java.util.*;
import java.io.*;
class prime
{
public static void main(String args[])throws Exception
{
int c=0,i;
System.out.println("enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
System.out.println(n+" is prime");
else
System.out.println(n+" is not prime");
}
}
Output:
enter a number:
7
7 is prime.
import java.io.*;
class prime
{
public static void main(String args[])throws Exception
{
int c=0,i;
System.out.println("enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
for(i=1;i<=n;i++)
{
if(n%i==0)
c++;
}
if(c==2)
System.out.println(n+" is prime");
else
System.out.println(n+" is not prime");
}
}
Output:
enter a number:
7
7 is prime.
java program to print a triangle
import java.util.*;
import java.io.*;
class triangle
{
public static void main(String args[])throws Exception
{
int i,j;
System.out.println("enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
Output:
enter a number
5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
import java.io.*;
class triangle
{
public static void main(String args[])throws Exception
{
int i,j;
System.out.println("enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println("");
}
}
}
Output:
enter a number
5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Java program to find out greatest of three numbers
import java.util.*;
import java.io.*;
class big
{
public static void main(String args[])throws Exception
{
System.out.println("enter 1st number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int a= Integer.parseInt(k.readLine());
System.out.println("enter 2nd number");
int b= Integer.parseInt(k.readLine());
System.out.println("enter 3rd number");
int c= Integer.parseInt(k.readLine());
if(a>=b && a>=c)
{
System.out.println(a+" is greater");
}
else if(b>=c && b>=a)
{
System.out.println(b+" is greater");
}
else
{
System.out.println(c+" is greater");
}
}
}
Output:
enter 1st number
3
enter 2nd number
7
enter 3rd number
1
7 is greater
import java.io.*;
class big
{
public static void main(String args[])throws Exception
{
System.out.println("enter 1st number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int a= Integer.parseInt(k.readLine());
System.out.println("enter 2nd number");
int b= Integer.parseInt(k.readLine());
System.out.println("enter 3rd number");
int c= Integer.parseInt(k.readLine());
if(a>=b && a>=c)
{
System.out.println(a+" is greater");
}
else if(b>=c && b>=a)
{
System.out.println(b+" is greater");
}
else
{
System.out.println(c+" is greater");
}
}
}
Output:
enter 1st number
3
enter 2nd number
7
enter 3rd number
1
7 is greater
java program for swapping two variables without using third variable
import java.util.*;
import java.io.*;
class swapping
{
public static void main(String args[])throws Exception
{
System.out.println("enter a value");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int a= Integer.parseInt(k.readLine());
System.out.println("enter b value");
int b= Integer.parseInt(k.readLine());
System.out.println("Before Swapping:");
System.out.println("a="+a+" "+"b="+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("After Swapping:");
System.out.println("a="+a+" "+"b="+b);
}
}
Output:
enter a value
3
enter b value
4
Before Swapping
a=3 b=4
After Swapping
a=4 b=3
import java.io.*;
class swapping
{
public static void main(String args[])throws Exception
{
System.out.println("enter a value");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int a= Integer.parseInt(k.readLine());
System.out.println("enter b value");
int b= Integer.parseInt(k.readLine());
System.out.println("Before Swapping:");
System.out.println("a="+a+" "+"b="+b);
a=a+b;
b=a-b;
a=a-b;
System.out.println("After Swapping:");
System.out.println("a="+a+" "+"b="+b);
}
}
Output:
enter a value
3
enter b value
4
Before Swapping
a=3 b=4
After Swapping
a=4 b=3
java program to find out reverse of a string
import java.util.*;
import java.io.*;
class reverse
{
public static void main(String args[])throws Exception
{
int i;
String s1="";
System.out.println("enter a string");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
String s= k.readLine();
int n=s.length();
for(i=n-1;i>=0;i--)
s1=s1+s.charAt(i);
System.out.println(s1);
}
}
Output:
enter a string
sample
elpmas
import java.io.*;
class reverse
{
public static void main(String args[])throws Exception
{
int i;
String s1="";
System.out.println("enter a string");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
String s= k.readLine();
int n=s.length();
for(i=n-1;i>=0;i--)
s1=s1+s.charAt(i);
System.out.println(s1);
}
}
Output:
enter a string
sample
elpmas
Palindrome Program in Java
import java.util.*;
import java.io.*;
class reverse
{
public static void main(String args[])throws Exception
{
int i;
String s1="";
System.out.println("enter a string");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
String s= k.readLine();
int n=s.length();
for(i=n-1;i>=0;i--)
s1=s1+s.charAt(i);
System.out.println(s1);
if(s1.equals(s))
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
}
}
Output:
enter a string
madam
madam
Palindrome
import java.io.*;
class reverse
{
public static void main(String args[])throws Exception
{
int i;
String s1="";
System.out.println("enter a string");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
String s= k.readLine();
int n=s.length();
for(i=n-1;i>=0;i--)
s1=s1+s.charAt(i);
System.out.println(s1);
if(s1.equals(s))
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
}
}
Output:
enter a string
madam
madam
Palindrome
Factorial program without recursion in java
import java.util.*;
import java.io.*;
class fact
{
public static void main(String args[])throws Exception
{
int i,fact=1;
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
for(i=1;i<=n;i++)
fact=fact*i;
System.out.println("factorial of "+n+" is:"+fact);
}
}
Output:
enter a number
5
factorial of 5 is:120
import java.io.*;
class fact
{
public static void main(String args[])throws Exception
{
int i,fact=1;
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
for(i=1;i<=n;i++)
fact=fact*i;
System.out.println("factorial of "+n+" is:"+fact);
}
}
Output:
enter a number
5
factorial of 5 is:120
Factorial program using recursion in java
import java.util.*;
import java.io.*;
class fact
{
public static void main(String args[])throws Exception
{
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
System.out.println("factorial of "+n+" is:"+factorial(n));
}
static int factorial(int k)
{
if (k == 0)
return 1;
return k * factorial(k-1);
}
}
output:
enter a number
5
factorial of 5 is:120
import java.io.*;
class fact
{
public static void main(String args[])throws Exception
{
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
System.out.println("factorial of "+n+" is:"+factorial(n));
}
static int factorial(int k)
{
if (k == 0)
return 1;
return k * factorial(k-1);
}
}
output:
enter a number
5
factorial of 5 is:120
Bubble Sort program in JAVA(Ascending order)
import java.util.*;
import java.io.*;
class sort
{
public static void main(String args[])throws Exception
{
int arr[]=new int[100];
int i,j,temp;
System.out.println("How many numbers you want to sort:");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
System.out.println("Enter the values one by one");
for(i=0;i<n;i++)
{
arr[i]=Integer.parseInt(k.readLine());
}
for(i=0;i<n-1;i++)
{
for(j=i;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("Numbers after sorting:");
for(i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}
output:
How many numbers you want to sort:
5
Enter the values one by one
4
3
7
6
1
Numbers after sorting:
1
3
4
6
7
import java.io.*;
class sort
{
public static void main(String args[])throws Exception
{
int arr[]=new int[100];
int i,j,temp;
System.out.println("How many numbers you want to sort:");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
System.out.println("Enter the values one by one");
for(i=0;i<n;i++)
{
arr[i]=Integer.parseInt(k.readLine());
}
for(i=0;i<n-1;i++)
{
for(j=i;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("Numbers after sorting:");
for(i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}
output:
How many numbers you want to sort:
5
Enter the values one by one
4
3
7
6
1
Numbers after sorting:
1
3
4
6
7
What are the differences between arrays and linked lists?
Difference between arrays and linked lists:
Arrays:
1. Arrays are static memory allocations. We can not change the array size at run time. If we declare the array size 10, then it can hold only 10 values.
2. The advantage of Arrays is, it supports random access. Means if we want to access 3rd element in an array, we can aceess it simply by using array[2],because array starts from 0.
Linked Lists:
1. Linked lists are dynamic memory allocations. We can allocate memory at run time.
2. The disadvantage of linked list is, it supports only sequential access. It does not support random access. If we want to access 3rd element, we need to traverse previous two nodes to access 3rd element.
Java program to findout whether the given number is armstrong or not
import java.util.*;
import java.io.*;
class armstrong
{
public static void main(String args[])throws Exception
{
int r,sum=0;
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
int k1=n;
while(n!=0)
{
r=n%10;
sum=sum+r*r*r;
n=n/10;
}
if(sum==k1)
System.out.println(k1+" is an armstrong number");
else
System.out.println(k1+" is not an armstrong number");
}
}
Output:
Enter a number
153
153 is an armstrong number
import java.io.*;
class armstrong
{
public static void main(String args[])throws Exception
{
int r,sum=0;
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
int k1=n;
while(n!=0)
{
r=n%10;
sum=sum+r*r*r;
n=n/10;
}
if(sum==k1)
System.out.println(k1+" is an armstrong number");
else
System.out.println(k1+" is not an armstrong number");
}
}
Output:
Enter a number
153
153 is an armstrong number
Java program to calculate binary value for a given number
import java.util.*;
import java.io.*;
class binary
{
public static void main(String args[])throws Exception
{
int i=0,sum=0;
int a[]=new int[100];
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
int k1=n;
while(n!=0)
{
a[i]=n%2;
i++;
n=n/2;
}
for(int j=i-1;j>=0;j--)
{
sum=sum*10+a[j];
}
System.out.println("Binary form of "+k1+" is:"+sum);
}
}
output:
enter a number
8
Binary form of 8 is 1000
import java.io.*;
class binary
{
public static void main(String args[])throws Exception
{
int i=0,sum=0;
int a[]=new int[100];
System.out.println("Enter a number");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(k.readLine());
int k1=n;
while(n!=0)
{
a[i]=n%2;
i++;
n=n/2;
}
for(int j=i-1;j>=0;j--)
{
sum=sum*10+a[j];
}
System.out.println("Binary form of "+k1+" is:"+sum);
}
}
output:
enter a number
8
Binary form of 8 is 1000
Using Break statement in java with example
Usage of Break:
break statement is used to terminate the loop based on some condition.The following loop uses the break statement.It will print values from 0 to 4.When i value equals to 5,the loop is terminated.
class break1
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
Using Continue statement in java with example
Usage of Continue:
continue statement is used to skip the execution of the loop based on some condition.The following loop uses the continue statement.It will print values from 0 to 9 except 5.When i value equals to 5,the loop is skipped.
class continue1
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
6
7
8
9
continue statement is used to skip the execution of the loop based on some condition.The following loop uses the continue statement.It will print values from 0 to 9 except 5.When i value equals to 5,the loop is skipped.
class continue1
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
6
7
8
9
java program to sort the characters in a string in ascending order
The following program illustrates the sorting of letters in a string.In this sort() method is used.It will sort all the letters in a string in ascending order.
import java.util.*;
import java.io.*;
import java.lang.String;
class sortletters
{
public static void main(String args[]) throws Exception
{
System.out.println("enter a string");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
String s=k.readLine();
char[] data=s.toCharArray();
java.util.Arrays.sort(data);
String s1=new String(data);
System.out.println("After Sorting");
System.out.println(data);
}
}
Output:
enter a string
example
After sorting
aeelmpx
How to Extract Characters from a String in java?
A String is a collection of individual characters. A character can be an alphabet, a digit or even a space. We can extract a single or multiple character(s) from a String. The following methods are used to extract characters from a string.
1. charAt();
2. getChars();
charAt():
The charAt() method is used to extract a single character from a String.
Example--
String s=“ Sample ”;
char c=s.charAt(1);
The charAt() method will extract a single character of the String based on the index.In this example the index is 1.So it will extract the 2nd character 'a'.Because index starts from 0.
Example:
class extract
{
public static void main(String args[])
{
String s="Sample";
char c=s.charAt(1);
System.out.println("The character extracted is "+c);
}
}
Output:
The character extracted is a
getChars():
The getChars() method extracts multiple characters from the String.
Syntax:
getChars(int StartPos, int EndPos, TargetArrayString, int StartArrayIndex);
Let us suppose that we have a string “Datamining”. You have to extract four characters “mini” from the string.For that starting position is 4 and ending position is 8.Here we are extracting multiple characters. Thus a character’s array is needed (An Array of characters can store as many characters as you wish!)
class extract
{
public static void main(String args[])
{
String s="Datamining";
char ch[]=new char[5];
s.getChars(4,8,ch,0);
System.out.println(ch);
}
}
Output:
mini
What is the use of this keyword in java?
'this' keyword can be used to differentiate the global variable and local variable.In the below example, first program is without using 'this' keyword and second program is using 'this' keyword.See the differences in the form of outputs.
Example:
class no_this
{
int a=10; //Here 'a' is a global variable
void take(int a)//Here 'a' is a local variable.within the function only it can be used
{
a=a;//here the local variable a is initialized itself.
}
void show()
{
System.out.println("a="+a); //here 'a' will print 10 only not 20
}
}
class test
{
public static void main(String args[])
{
no_this n=new no_this();
n.take(20);//it calls the take() method and assigns 20 to 'a'
n.show();
}
}
output:
a=10;
In the above example we are not using 'this' keyword so the local variable 'a' gets initialized itself.If we use 'this' keyword,we can easily differentiate the local and global variables.See the following example.
class with_this
{
int a=10; //Here 'a' is a global variable
void take(int a)//Here 'a' is a local variable.within the function only it can be used
{
this.a=a;//here the local variable 'a' is initialized to this.a(means global variable).
}
void show()
{
System.out.println("a="+a); //here 'a' will print 20
}
}
class test
{
public static void main(String args[])
{
with_this n=new with_this();
n.take(20);//it calls the take() method and assigns 20 to 'a'
n.show();
}
}
output:
a=20
What are the pure and impure functions?
Pure Functions:
Pure functions do not modify their arguments or output. The result of a pure function call is the return value.
Impure Functions:
Just opposite to pure function
What is call-by-value and call-by-reference in java?
Call by Value:
When we pass a variable of int, float or any other type of data to a method or some constant values like sample(5,10), they are all passed by value. A copy of variable’s value is passed to the receiving method and hence any changes made to the values do not affect the actual variables.
Example:
class call_by_val
{
int n1,n2;
public void get(int x,int y)
{
x=x*x; //Changing the values of passed arguments
y=y*y; //Changing the values of passed arguments
}
}
class test
{
public static void main(String args[])
{
int a,b;
a=5;
b=10;
System.out.println("Initial Values of a & b "+a+" "+b);
call_by_val obj=new call_by_val();
obj.get(a,b);
System.out.println("Final Values "+a+" "+b);
}
}
output:
Initial Values of a & b 5 10
Final Values 5 10
Call by Reference:
Objects are always passed by reference. When we pass a value by reference, the reference or the memory address of the variables is passed. Thus any changes made to the argument causes a change in the values which we pass.
Example:
class call_by_ref
{
int n1,n2;
public void get(int a,int b)
{
n1=a;
n2=b;
}
public void doubleit(call_by_ref temp)
{
temp.n1=temp.n1*2;
temp.n2=temp.n2*2;
}
}
class test
{
public static void main(String args[])
{
int x=5,y=10;
call_by_ref obj=new call_by_ref();
obj.get(x,y); //Pass by Value
System.out.println("Initial Values are: ");
System.out.println(+obj.n1);
System.out.println(+obj.n2);
obj.doubleit(obj); //Pass by Reference
System.out.println("Final Values are:");
System.out.println(+obj.n1);
System.out.println(+obj.n2);
}
}
output:
Initial Values are:
5
10
Final Values are:
10
20
Write a java program to print fibonacci series?
The following program prints fibonacci series.
import java.io.*;
class fibo
{
public static void main(String args[])throws Exception
{
int k=1,i=0,j=1;
System.out.println("Enter a value");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(b.readLine());
System.out.println("fibonacci series is:");
System.out.print(k+" ");
for(int k1=0;k1<n-1;k1++)
{
k=i+j;
System.out.print(k+" ");
i=j;
j=k;
}
}
}
output:
Enter a value
5
fibonacci series is:
1 1 2 3 5
import java.io.*;
class fibo
{
public static void main(String args[])throws Exception
{
int k=1,i=0,j=1;
System.out.println("Enter a value");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
int n= Integer.parseInt(b.readLine());
System.out.println("fibonacci series is:");
System.out.print(k+" ");
for(int k1=0;k1<n-1;k1++)
{
k=i+j;
System.out.print(k+" ");
i=j;
j=k;
}
}
}
output:
Enter a value
5
fibonacci series is:
1 1 2 3 5
What are the uses or advantages of java language?
Java is a fun language. Let’s look at some of the reasons:
1.Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).
2.Object Oriented (OO).
3.Better portability than other languages across operating systems.
4.Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised APIs (Application Program Interfaces).
1.Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).
2.Object Oriented (OO).
3.Better portability than other languages across operating systems.
4.Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised APIs (Application Program Interfaces).
Explain Java class loaders?
Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.
Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.
Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.
Java program to calculate sum of digits of a given number
The following is the java program to calculate sum of digits in a given number. It is easy to calculate sum of digits. first we will read the input number by using buffered reader and we will store that number in a variable. Later we will extract each digit by using %10. Every time it returns last digit of a number. This process is done until all digits are covered.
/* Simple Java Program To Find the Sum of digits of number */
import java.io.*;
class calcsum
{
public static void main(String args[]) throws Exception
{
int sum, i,a,d;
System.out.println("Enter A Number ");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(k.readLine());
sum = 0;
while(a!=0)
{
d = a%10;
a = a/10;
sum=sum + d;
}
System.out.println("Sum of Digits :"+sum);
}
}
output:
java program to read a text file
This is the java program to read a text file and it writes to the command prompt. We use fileinputstream to read a text file. The read() function extracts the ascii value of each character in a file. We have to convert that ascii value into its original form. First we have to take the sample text document in any folder but we have to declare the path of text document.
/* java program to read a text file */
import java.io.*;
class readfile
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream("C:/sampath/sample.txt"); //You give your text file path
}
catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i =fin.read();
if(i!=-1)
System.out.print((char)i);
} while(i!=-1);
}
}
Output:
Java program to find subsets
This is the java program to find subsets. This is simple and small code. Subsets program can be used in many logical applications.Consider the following subsets program in java.
/* java program to find subsets */
import java.io.*;
public class subset
{
public static void main(String[] args) throws IOException
{
int tot_elements = 0;
int count = 0;
System.out.println("Enter Total No Of Elements:");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
tot_elements = Integer.parseInt(bf.readLine());
final int loopBound = (1 << tot_elements) - 1;
for (int i = 0; i <= loopBound; i++)
{
printSubset(i, tot_elements);
count++;
}
System.out.println("Total No Of Elements:"+count);
}
private static void printSubset(int ordinal, int tot_elements)
{
if (ordinal == 0) // throw away empty set
return;
boolean firstElem = true;
System.out.print('{');
int mask = 1;
final int loopBound = (1 << tot_elements) - 1;
for (int i = 0; i <= loopBound; i++)
{
if ((ordinal & mask) > 0)
{
if (!firstElem)
{
System.out.print(", ");
}
else
{
firstElem = false;
}
System.out.print((int) (1 + i));
}
mask <<= 1;
}
System.out.println('}');
}
}
Output:
Write a java program to reverse a given number?
This is the java program to find the reverse of a number. It can be done by using mod operator ,it returns the remainder. if we use that mode with 10 , then it returns last digit of a number. So we will extract all digits in a number and multiply with 10. Consider the following program to find reverse of number in java.
/* java program to find reverse of number */
import java.io.*;
class reverse
{
public static void main(String args[]) throws Exception
{
int sum, i,a,d;
System.out.println("Enter A Number ");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(k.readLine());
sum = 0;
while(a!=0)
{
d = a%10;
sum=sum*10+d;
a = a/10;
}
System.out.println("Reverse Of a number :"+sum);
}
}
Output:
/* java program to find reverse of number */
import java.io.*;
class reverse
{
public static void main(String args[]) throws Exception
{
int sum, i,a,d;
System.out.println("Enter A Number ");
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(k.readLine());
sum = 0;
while(a!=0)
{
d = a%10;
sum=sum*10+d;
a = a/10;
}
System.out.println("Reverse Of a number :"+sum);
}
}
Output:
Write Quick sort program in java language?
This is the quick sort program in java language.
We sort the array
A = (38 81 22 48 13 69 93 14 45 58 79 72)
with quicksort, always choosing the pivot element to be the element in position (left+right)/2. The partitioning during the top-level call to quicksort() is illustrated on the next page. During the partitioning process,
i) Elements strictly to the left of position lo are less than or equivalent to the pivot element (69).
ii) Elements strictly to the right of position hi are greater than the pivot element.
When lo and hi cross, we are done. The final value of hi is the position in which the partitioning element ends up. An asterisk indicates an element compared to the pivot element at this step.
A = (38 81 22 48 13 69 93 14 45 58 79 72)
with quicksort, always choosing the pivot element to be the element in position (left+right)/2. The partitioning during the top-level call to quicksort() is illustrated on the next page. During the partitioning process,
i) Elements strictly to the left of position lo are less than or equivalent to the pivot element (69).
ii) Elements strictly to the right of position hi are greater than the pivot element.
When lo and hi cross, we are done. The final value of hi is the position in which the partitioning element ends up. An asterisk indicates an element compared to the pivot element at this step.
Quicksort Program:
/* write quick sort program in java language */
public class QuickSort
{
public static void main(String a[])
{
int i;
int elements[] = {14,7,8,98,43,1,3,75,13};
System.out.println("Values Before the sorting:\n");
for(i = 0; i < elements.length; i++)
System.out.print( elements[i]+" ");
System.out.println();
quick_srt(elements,0,elements.length-1);
System.out.print("Values after the sorting:\n");
for(i = 0; i <elements.length; i++)
System.out.print(elements[i]+" ");
System.out.println();
}
public static void quick_srt(int array[],int low, int n)
{
int lo = low;
int hi = n;
if (lo >= n)
{
return;
}
int mid = array[(lo + hi) / 2];
while (lo < hi)
{
while (lo<hi && array[lo] < mid)
{
lo++;
}
while (lo<hi && array[hi] > mid)
{
hi--;
}
if (lo < hi)
{
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}
}
if (hi < lo)
{
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo+1 : lo, n);
}
}
Output:
What are the differences between C and Java?
Differences between C and Java: The following are the simple differences between C and Java
C:
1. C is a platform dependent.
2. C does not uses classes.
3. C does not support encapsulation and polymorphism.
4. C does not contain exception handling mechanism.
5. C is a procedural language.
Java:
1. Java is platform independent.
2. Java uses classes.
3. Java supports encapsulation and polymorphism.
4. Java contains exception handling mechanism.
5. Java is an object oriented language.
C:
1. C is a platform dependent.
2. C does not uses classes.
3. C does not support encapsulation and polymorphism.
4. C does not contain exception handling mechanism.
5. C is a procedural language.
Java:
1. Java is platform independent.
2. Java uses classes.
3. Java supports encapsulation and polymorphism.
4. Java contains exception handling mechanism.
5. Java is an object oriented language.
What is a data type?
Data Type: The data type of a programming element refers to what kind of data it can hold and how the data is stored. If we take integer data type, it can hold only integer values. In the same way, String data type can hold only string values. Data types are divided into two types.
1. Primitive data types
2. Reference data types
1.Primitive data types: Primitive data types are predefined data types. Always they hold only one type of data. Suppose if a variable is declared as integer, It can hold only integer values.Following are the examples of primitive data types.
Example:
int
String
float
double
char
boolean
byte
short
2. Reference data types: The reference data type is a variable that can contain the reference or an address of dynamically created object. This data type is not predefined.
Example:
Array
class
interface
What is a thread? and how to create a thread in java?
Thread: A thread is a light weight process. It represents execution of statements. Threads are called light weight because they utilize minimum resources of the system.
How to create a Thread:
Threads can be created in two ways.
1. By inheriting from thread class
2. By using runnable interface
1.By inheriting from thread class:
class Mythread extends Thread
{
public void run()
{ for(int i=0;i<1000;i++)
{
System.out.println((i);
}
}
}
class demo
{
public static void main(String args[])
{
Mythread obj=new Mythread();
Thread t=new Thread(obj);
t.start();
}
}
In the above example, Thread is created using Thread object_name=new Thread(class_object) statement. After creating a thread, we invoke thread by calling start() method. Then run() method starts execution when start() method is called. A thread is terminated when it comes out of run() method.
2. By using runnable interface:
class Mythread implements Runnable
{
public void run()
{ for(int i=0;i<1000;i++)
{
System.out.println((i);
}
}
}
class demo
{
public static void main(String args[])
{
Mythread obj=new Mythread();
Thread t=new Thread(obj);
t.start();
}
}
What is Run time polymorphism in java?
Run time polymorphism: If the polymorphism exhibits at run time, then it is called run time polymorphism. Method overriding is an example of run time polymorphism. If we use the same method in subclass, then subclass method will override the super class method. To avoid that we can use run time polymorphism. So java virtual machine knows which method to call at run time.
Example:
class base
{
void show()
{
System.out.println("This is base class") ;
}
}
class sub extends base
{
void show()
{
System.out.println("This is sub class") ;
}
}
class runtimepoly
{
public static void main(String args[])
{
sub ob=new sub();
ob.show();
sub ob1=new sup();
ob1.show();
}
}
Output:
This is sub class
This is base class
In the above example, when we call ob.show(), it will call only sub class method. Because the sub class method will over ride the super class method. To avoid that we will invoke super class by creating an object, so now ob1 will call super class method.
What is Static Ploymorphism in java?
Static Ploymorphism: Ability to take more than one form is called polymorphism. if the polymorphism exhibits at compile time, then it is called static polymorphism. Method overloading is an example of static polymorphism.
Example:
class sumvalue
{
int s;
void sum(int x,int y)
{
s=x+y;
System.out.println("sum of two integers is:"+s)
}
void sum(int x,int y,int z)
{
s=x+y+z;
System.out.println("sum of three integers is:"+s);
}
}
class staticpolymorphism
{
public static void main(String args[])
{
sumvalue v=new sumvalue();
v.sum(2,3);
v.sum(2,3,4);
}
}
Output:
sum of two integers is:5
sum of three integers is:9
What is polymorphism in java with example?
Polymorphism: Ability to take more than one form is called polymorphism. In the following example the method area() is in two forms.In first form,it is having two arguments and second one is having single argument. So this mechanism is called polymorphism.
Example:
area(int l,int b)
{
}
area(int r)
{
}
Subscribe to:
Posts (Atom)