Programming Interview Questions

Write the Java code to declare any constant (say gravitational constant) and to get its value.

General

Last Updated on Thursday, 25 February 2010 22:37 Written by Rahul Mehra Thursday, 25 February 2010 22:05

Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}

 

How can we replace characters in a string in Java?

General

Last Updated on Thursday, 25 February 2010 22:37 Written by Rahul Mehra Thursday, 25 February 2010 21:24

// Replace all occurrences of 'a' with 'o'
String newString = string.replace('a', 'o');
Replacing Substrings in a String
static String replace(String str,
String pattern, String replace) {
int s = 0;
int e = 0;
StringBuffer result = new StringBuffer();
while ((e = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e+pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
Converting a String to Upper or Lower Case
// Convert to upper case
String upper = string.toUpperCase();
// Convert to lower case
String lower = string.toLowerCase();
Converting a String to a Number
int i = Integer.parseInt("123");
long l = Long.parseLong("123");
float f = Float.parseFloat("123.4");
double d = Double.parseDouble("123.4e10");
Breaking a String into Words
String aString = "word1 word2 word3";
StringTokenizer parser =
new StringTokenizer(aString);
while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
3. Searching a String
String string = "aString";
// First occurrence.
int index = string.indexOf('S'); // 1
// Last occurrence.
index = string.lastIndexOf('i'); // 4
// Not found.
index = string.lastIndexOf('z'); // -1

 

Login Form (Can use your Gmail Acct)

Latest Comments

Copyright © 2017 Interview Questions, Tutorials, Certification Questions. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.