Wednesday, 25 March 2015
Monday, 23 March 2015
Difference between for each loop and an Iterator
package com.manish;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
List lst=new ArrayList();
lst.add("Manish");
lst.add("Nitesh");
lst.add("Rupesh");
lst.add("Shubham");
lst.add("prerit");
// Using for each we don't have a chance to remove object from the list.
for(Object l:lst)
{
// lst.remove("Rupesh"); /* Not OK
java.util.ConcurrentModificationException */
}
System.out.println(lst);
// O/P [Manish, Nitesh, Rupesh, Shubham, prerit]
// Using iterator we have a chance to remove object from the list while iterating using iterator object.
Iterator it=lst.iterator();
while(it.hasNext())
{
Object obj=it.next();
if(obj.equals("Rupesh"))
{
lst.remove("Rupesh"); /* Not OK it will throw
java.util.ConcurrentModificationException */
it.remove(); // OK
}
}
System.out.println(lst);
// O/P [Manish, Nitesh, Shubham, prerit]
}
}
Note: In addition,in the case of for each loop we can access the elements in the forward direction only.If you want to access the elements in both forward and reverse direction then you can use listIterator interface (subclass of Iterator interface).
Saturday, 21 March 2015
Q. How Map allows primitive or integer as key ?
Ans:Map allows object as key and value.In the case of primitive like int, autoboxing (introduced in java 1.5) is done by the compiller.So primitive int is converted to Integer object by the compiller automatically.Thus, Map allows primitive int as key.
e.g package com.manish;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Map mp=new HashMap();
mp.put(1, 2); // OK from 1.5
}
}
The same code will give compillation error when compilled in java 1.4 or lower.
e.g package com.manish;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Map mp=new HashMap();
mp.put(1, 2); // Not OK compillation error in 1.4 version
}
}
Friday, 20 March 2015
Q.Given an array of size 1000 having no's between 1 to 9. Find the number of times each element is repeated in the most efficient way?
package com.manish;
import java.util.Arrays;
public class OccurenceOfNumber
{
public static void main(String[] args)
{
int arr[]={2,5,8,9,2,1,1,5,5};
Arrays.sort(arr);
for(int i=1;i<arr.length;i++)
{
int low=binarySearchFirst(arr,i);
int high=binarySearchLast(arr,i);
int total=(high>=low && high!=-1 && low!=-1)?(high-low+1):0;
System.out.println(i+" : "+total+" times");
}
}
public static int binarySearchFirst(int arr[],int k)
{
int begin=0;
int end=arr.length-1;
int mid=-1;
while(begin<=end)
{
mid=(begin+end)/2;
if(arr[mid]< k)
{
begin=mid+1;
}
else{
end=mid-1;
}
}
return (begin<=end && begin>=0 && arr[begin]!=k)? -1:begin;
}
public static int binarySearchLast(int arr[],int k)
{
int begin=0;
int end=arr.length-1;
int mid=-1;
while(begin<=end)
{
mid=(begin+end)/2;
if(arr[mid] > k)
{
end=mid-1;
}
else {
begin=mid+1;
}
}
return (end>=begin && end>=0 && arr[end]!=k)? -1:end;
}
}
Q. Given no's 12345.find the sum of all the digits example- 1+2+3+4+5.
package com.manish;
import java.util.Scanner;
public class SumOfDigits
{
public static void main(String[] args)
{
int num=new Scanner(System.in).nextInt();
int sum=0;
int input=num;
while(input !=0)
{
int lastdigit=input%10;
sum=sum+lastdigit;
input=input/10;
}
System.out.println(sum);
}
}
Q. Find factorial using recursion and iteration ?
package com.manish;
public class Factorial
{
public static void main(String[] args)
{
System.out.println(factorialRecursion(3));
System.out.println(factorialIteration(3));
}
// using iteration
public static int factorialRecursion(int num)
{
if(num==0)
{
return 1;
}
return num*factorialRecursion(num-1);
}
public static int factorialIteration(int num)
{
int res=1;
while(num !=0)
{
res=res*num;
num--;
}
return res;
}
}
Q. You are given an array of integers, containing both +ve and -ve numbers. You need to find the two elements such that their sum is closet to zero.
package com.manish;
import java.util.Arrays;
public class MinTest
{
public static void main(String[] args)
{
int arr[]=new int[]{5,3,1,-8,-8,6};
minSum(arr);
}
public static void minSum(int arr[])
{
int l, r , min_sum,min_left,min_right,tempsum = 0;
if(arr.length<2)
{
System.out.println("invalid input");
}
Arrays.sort(arr);
l=0;r=arr.length-1;
min_sum=arr[l]+arr[r];
min_left=l;
min_right=r;
while(l<r)
{
tempsum=arr[l]+arr[r];
if(Math.abs(tempsum) < Math.abs(min_sum))
{
min_left=l;
min_right=r;
min_sum=tempsum;
}
if(tempsum < 0) l++;
else r--;
}
System.out.println(arr[min_left]+" "+arr[min_right]);
}
}
Q. Write a program to find the fibonacci series by recurssion and iterative way?
package com.manish.fiboseries;
import java.util.Scanner;
public class FibonacciSeries
{
public static void main(String[] args)
{
int num=new Scanner(System.in).nextInt(); /* inter the number upto
which fibonacci series has to be calculated */
for(int i=1;i<=num;i++) //
{
System.out.print(fibonacciIteration(i)+" ");
}
System.out.println("");
for(int i=1;i<=num;i++)
{
System.out.print(fibonacciRecursion(i)+" ");
}
}
public static int fibonacciIteration(int number)
{
if(number == 1 || number == 2)
{
return 1;
}
int fib1=1, fib2=1, fibonacci=1;
for(int i= 3; i<= number; i++)
{
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
public static int fibonacciRecursion(int number) //recursion method
{
if(number == 1 || number == 2)
{
return 1;
}
return fibonacciRecursion(number-1)+ fibonacciRecursion(number-2);
}
}
Wednesday, 18 March 2015
Q. what is identifier in java?
Ans: Any name in java is called an identfier in java.It may be a method name,class name,variable name etc.
The allowed characters in identifier are :
1. Alphabets a to z both upper and lower case.
2.Digits 0-9
3.$ and _
e.g- Customer_name, _$Car,_Car etc..
If we are using other then these we will get a compillation error.
Identifier cannot start with digits.
e.g- 123total // compillation error
java identifiers are case sensitive.
e.g- student and Student are different.
Reserved words cannot be used as identifiers.
All predefined java class name and interface name we can use as identifier but not recommendable.
e.g- class TestIdentifier
{
int String=25; // OK
System.out.println(String);
}
Q. Can you execute java application without using main() method ?
Ans: • Yes, (using static block) before java 7
• No, from java 7.
Tuesday, 17 March 2015
Q. Is java pure or fully object oriented programing language?
Ans: No, java is not fully object oriented programing language because it supports Primitive data types such as int, byte, long... etc,which are not objects.Smalltalk is a pure OOP language where there are no primitive data types, and boolean, int ... etc are all objects.
Q. What is class, object and instance ?
Ans: Class: class is a blueprint or template which is used to create objects.For example- Suppose you have to make a car and so you made a protype or blueprint on paper that the car will have four wheels,one starring,two headlights etc...etc..Basically, a class will consists of fields,methods and constructors.Field is used to hold the state of the class. Method is used to represent the behavior of the class e.g Car have state (current speed, current gear) and behavior (applying brake, changing gear). Constructor is used to create a new Instance of the Class.
Objects: Now, using that protype or blueprint you can make N number of cars which is nothing but objects.Any entity that has state and behavior is known as an object. An object stores its state in fields and exposes its behavior through methods e.g Car have state (current speed, current gear) and behavior (applying brake, changing gear).
Instance: Now, will that car created on paper run ...?.No, because it is on paper.An actual object in memory is called an instance.An instance is a unique copy of a class that represents an object. When a new instance of a class is created, the JVM will allocate memory for that class instance.The instance of the object is created using new operator.
e.g Car c=new Car();
Q. What is keywords in java?How many keywords are there in java?
Q. What is keywords in java?How many keywords are there in java?
Ans: Keywords are the reserved words in java language that have a predefined meaning.Keywords cannot be used as names for variables, methods, classes, or as any other identifier.There are total 50 keywords in java. Example: abstract, assert, break, case, catch, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if,implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, switch, super, synchronized, this, throw, throws,transient,try,void, volatile, while,do.
Q. Is JVM platform independent or dependent?
Ans: JVM is platform dependent.Every OS e.g Macintosh, windows or Linux etc. has different JVMs.Java compiller converts the java source file into .class file which is nothing but Byte code or intermediate code which is understood by JVM.Now, JVM converts the byte code into machine code which is platform specific. Hence,JVM is platform dependent.
Difference between JDK, JRE and JVM
Q. What is the difference between JDK, JRE and JVM ?
Ans: JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools e.g javac,java etc.
JRE is an acronym for Java Runtime Environment.The JRE provides the libraries, Java virtual machine, and other components necessary to run applets and applications written in the Java programming language.
JVM is the acronym for Java virtual machine.It is an abstract computing machine that has an instruction set and manipulates memory at run time.JVM is platform dependent.
Why java is called Platform Independent OR compile once run anywhere programming language?
Q. Why java is called Platform Independent OR compile once run anywhere programming language?
Ans: When a java program is compilled a .class file is generated.This .class file contains the byte code or the intermediate code which is understood by JRE installed on the operating sytems e.g Macintosh, windows or Linux etc. Hence java is called Platform Independent OR compile once run anywhere programming language.
Q. What is Java technology and where it is used?
Q. What is Java technology and where it is used?
Ans: Java is a platform independent programming language and a computing platform.It was first released by Sun Microsystems as java 1.0 in 1995.It is used in Mobile,Embedded System, Smart Card,Robotics,Games etc.
Subscribe to:
Posts (Atom)