Showing posts with label Java Exapmle. Show all posts
Showing posts with label Java Exapmle. Show all posts

Saturday 10 August 2013

Top Most Towers of Hanoi using Java


package com.algorithmes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* The Towers of Hanoi problem using Recursion in Java
* Author: Guru
*/
public class TowersOfHanoi {

/**
* @param args
*/
static int moves =1;
public static void main(String[] args) {
int n=0;
System.out.println("Enter the value for N:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {

//Read the value
n=Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// The towers is a function to solve the Towers of Henoi
towers(n,'A','B','C');
}

/**
* The recursive method for the towers problem
* @param n
* @param c
* @param d
* @param e
*/
private static void towers(int n, char from, char to, char via) {
if(n==1)
System.out.println("Move "+moves+++" from "+from+" to "+to);
else{
towers(n-1,from,via,to);
System.out.println("Move "+moves+++" from "+from+" to "+to);
towers(n-1,via,to,from);

}
}

}

The output of the Towers of Hanoi using Recursion in Java is:

Enter the value for N:
3
Move 1 from A to B
Move 2 from A to C
Move 3 from B to C
Move 4 from A to B
Move 5 from C to A
Move 6 from C to B
Move 7 from A to B

Friday 9 August 2013

Top Most Java Interview Questions Programs - 1

Question 1

Given:
public class Person {
private name;
public Person(String name) {
this.name = name;
}
public int hashCode() {
return 420;
}
}

Which is true?

A. The time to find the value from HashMap with a Person key depends on the size of the map.
B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
C. Inserting a second Person object into a HashSet will cause the first Person object to be removed as a duplicate.
D. The time to determine whether a Person object is contained in a HashSet is constant and does NOT depend on the size of the map.

Question 2

Given:
interface TestA { String toString(); }
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() { return “test”; }
});
}
 }

What is the result?
A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.

Question 3

Given:
String #name = “Jane Doe”;
int$age=24;
Double_height = 123.5;
double~temp = 37.5;

Which two are true? (Choose two.)
A. Line 35 will not compile.
B. Line 36 will not compile.
C. Line 37 will not compile.
D. Line 38 will not compile.
Answer: AD

Question 4

A JavaBeans component has the following field:

private boolean enabled;

Which two pairs of method declarations follow the JavaBeans standard for accessing this field? (Choose two.)

A. public void setEnabled( boolean enabled)
public boolean getEnabled()
B. public void setEnabled( boolean enabled)
public void isEnabled()
C. public void setEnabled( boolean enabled)
public boolean isEnabled()
D. public boolean setEnabled( boolean enabled)
public boolean getEnabled()
Answer: AC

Question 5

Given:
public class Plant {
private String name;
public Plant(String name) { this.name = name; }
public String getName() { return name; }
}

public class Tree extends Plant {
public void growFruit() { }
public void dropLeaves() { }
}

Which is true?
A. The code will compile without changes.
B. The code will compile if public Tree() { Plant(); } is added to the Tree class.
C. The code will compile if public Plant() { Tree(); } is added to the Plant class.
D. The code will compile if public Plant() { this(”fern”); } is added to the Plant class.
E. The code will compile if public Plant() { Plant(”fern”); } is added to the Plant class.
Answer: D

Question 6

Given:
int x= 10;
do {
x--;
} while(x< 10);

How many times will line 37 be executed?
A. ten times
B. zero times
C. one to me times
D. more than ten times
Answer: D

Question 7

Given:
try {
// some code here
} catch (NullPointerException e1) {
System.out.print(”a”);
} catch (RuntimeException e2) {
System.out.print(”b”);
} finally {
System.out.print(”c”);
}
What is the result if a NullPointerException occurs on line 34?
A. c
B. a
C. ab
D. ac
E. bc
F. abc
Answer: D

Question 8

Given:
static void test() {
try {
String x=null;
System.out.print(x.toString() +“ “);
}
finally { System.out.print(“finally “); }
}
public static void main(String[] args) {
try { test(); }
catch (Exception ex) { System.out.print(”exception “); }
}
What is the result?
A. null
B. finally
C. null finally
D. Compilation fails.
E. finally exception
Answer: E

Question 9

Given:
public class MyLogger {
private StringBuilder logger = new StringBuuilder();
public void log(String message, String user) {
logger.append(message);
logger.append(user);
}
}

The programmer must guarantee that a single MyLogger object works properly for a multi-threaded system. How must this code be changed
to be thread-safe?
A. synchronize the log method
B. replace StringBuilder with StringBuffer
C. No change is necessary, the current MyLogger code is already thread-safe.
D. replace StringBuilder with just a String object and use the string concatenation (+=) within the log method

Answer: A

Question 10

Assuming that the serializeBanana() and the deserializeBanana()
methods will correctly use Java serialization and given:
import java.io.*;
class Food implemertts Serializable {int good = 3;}
class Fruit externds Food {int juice = 5;}
public class Banana extends Fruit {
int yellow = 4;
public static void main(String [] args) {
Banana b = new Banana(); Banana b2 = new Banana();
b.serializeBanana(b); // assume correct serialization
b2 = b.deserializeBanana(); // assume correct
System.out.println(”restore “+b2.yellow+ b2.juice+b2.good);
}
// more Banana methods go here
 }
What is the result?
A. restore 400
B. restore 403
C. restore 453
D. Compilation fails.
E. An exception is thrown at runtime.
Answer: C

Top Most Fibonacci Series Java Example


package com.algo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
* Program for Fibonacci Series using Java
* Author: Guru.
* Date: 10-01-2011
*/

public class FibonacciSeries {

/**
* @param args
*/
public static void main(String[] args) {
int n=0;
System.out.println("Please Enter value for N:");
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
try {

//Read the febonacci value
n=Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//print the Fibonacci series numbers
System.out.println("The Febonicci Series is:");
for(int i=0;i<=n;i++)
{
System.out.print(febonacci(i)+" ");
}

}

/*
* The method for computing the Febonacci Series.
* input: int
*/
private static int febonacci(int n) {
if(n<=0) return 0;
else if(n==1) return 1;
else return(febonacci(n-1)+febonacci(n-2));
}

}

Output of Febonacci Series Java Program:

Please Enter value for N:
8
The Febonicci Series is:
0 1 1 2 3 5 8 13 21


LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt