Saturday, August 22, 2015
Wednesday, July 2, 2014
Integer Literal - Octals
What is the Output of the below Program:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The literal 08 of type int is out of range
at OcatalSample.main(OcatalSample.java:7)
Why??
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
Octal representation in java(base 8) :
An integer literal prefixed with 0 is treated as octal. It means when an integer literal starts with 0 in Java, it's assumed to be in octal notation. The digits 8 and 9 are illegal in octal—the digits can range only between 0 and 7.
In the above example #line7 gives an error, because as per above line range of octal is 0 to 7 only.
Note: Generally in octal representation, 7 + 1 is 10.
//OcatalSample.java
public class OcatalSample{
public static void main(String []args){
int i = 012;
int j = 034;
int k = 056;
int m = 08;
System.out.println("i=" +i + ", j="+j+ ", k="+k+ ", m="+m);
}
}
public class ReverseNumber {
public static void main(String[] args) {
int number = 987;
System.out.println("Reverse of given number is: "+
getReverseNumber(number));
}
private static int getReverseNumber(int number) {
int reverseNumber = 0;
while (number > 0) {
int reminder = number % 10;
reverseNumber = reverseNumber * 10 + reminder;
number = number / 10;
}
return reverseNumber;
}
}
//Output:
//Reverse of given number is: 789
Output: It won’t compile. It gives below compilation errorException in thread "main" java.lang.Error: Unresolved compilation problem:
The literal 08 of type int is out of range
at OcatalSample.main(OcatalSample.java:7)
Why??
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
Octal representation in java(base 8) :
An integer literal prefixed with 0 is treated as octal. It means when an integer literal starts with 0 in Java, it's assumed to be in octal notation. The digits 8 and 9 are illegal in octal—the digits can range only between 0 and 7.
In the above example #line7 gives an error, because as per above line range of octal is 0 to 7 only.
Note: Generally in octal representation, 7 + 1 is 10.
Wednesday, June 18, 2014
String comparison tip
In Java if you actually want to test whether two strings
have the same value you should use .equals(). It checks value equality.
I think most of the people knew it.
Today I
want to add a very valuable tip:
If you have strings or constants to compare, always put them first in the equals clause.
//StringComparisonTip.java
public class StringComparisonTip {
public static void main(String[] args) {
// Recommended String comparison
if("Venkatesh".equals(getMyName())){
System.out.println("We are equal");
}
// It is Correct but it may be throws NPE at runtime
if(getMyName().equals("Venkatesh")){
System.out.println("We are equal");
}
}
public static String getMyName(){
return null;
}
}
In the above code line #5 (if("Venkatesh".equals(getMyName()))) is much better than the line #9 (if(getMyName().equals("Venkatesh"))) because in the second case getMyName() may be null and throws an java.lang.NullPointerException while in the first case it doesn't matter if getMyName() is null.
Note: I am not saying second one is wrong but I am saying it is not recommended by Java Guru's(Who has great knowledge in Java). Both are syntactically correct and you never get compilation error.
Note: I am not saying second one is wrong but I am saying it is not recommended by Java Guru's(Who has great knowledge in Java). Both are syntactically correct and you never get compilation error.
Tuesday, June 10, 2014
Count occurrence of an element
Write a program to count the total number of duplicated entries in a List.
For Example :
Input List of countries : japan,usa,uae,japan,uae,usa,australia
Expected output:
japan:2
usa:2
uae:2
australia:1
Solutions:
Solution 1:
1) Java API provides a class called Collections. This class contains static utility methods for manipulating collections. It provides a static method for counting the number of elements in specified collection, as you can see below for more information.
Solution 2:
For Example :
Input List of countries : japan,usa,uae,japan,uae,usa,australia
Expected output:
japan:2
usa:2
uae:2
australia:1
Solutions:
Solution 1:
1) Java API provides a class called Collections. This class contains static utility methods for manipulating collections. It provides a static method for counting the number of elements in specified collection, as you can see below for more information.
static int | frequency(Collection<?> c, Object o)Returns the number of elements in the specified collection equal to the specified object. c - the collection in which to determine the frequency of o o - the object whose frequency is to be determined |
// CountDuplicates.java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class CountDuplicates {
public static void main(String[] args) {
String[] listOfArray =
{ "japan", "usa", "uae", "japan", "uae", "usa", "australia" };
List list = Arrays.asList(listOfArray);
System.out.println("Frequency of each country ");
Set uniqueSet = new LinkedHashSet(list);
for (String countryName : uniqueSet) {
System.out.println(countryName + ": "
+ Collections.frequency(list, countryName));
}
}
}
//Output::
//Frequency of each country
//japan: 2
//usa: 2
//uae: 2
//australia: 1
Solution 2:
// CountDuplicates1.java
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Map;
public class CountDuplicates1 {
public static void main(String[] args) {
String[] listOfArray =
{ "japan", "usa", "uae", "japan", "uae", "usa", "australia" };
Map<String, Integer> map = new LinkedHashMap<String,Integer>();
for( String countryName : listOfArray){
int count = 0;
if(map.get(countryName) != null){
count = map.get(countryName);
}
map.put(countryName, count+1);
}
for (Entry countryEntry : map.entrySet()) {
System.out.println(countryEntry.getKey()+ ": "
+ countryEntry.getValue() );
}
}
}
//Output::
//Frequency of each country
//japan: 2
//usa: 2
//uae: 2
//australia: 1
Monday, June 9, 2014
Swap two numbers
Solutions:
1) Using temporary variable / Using extra space
2) Without using temporary variable / Without using extra space
a) Using arithmetic operators
b) Using bitwise operator
Solution 1: Using temporary variable
We can use "*" & "/" operators also instead of "+" & "-". Check the above program lines 14, 15 and 16 for the reference. But problem with "/" operator is it gives java.lang.ArithmeticException: / by zero Exception for "b" value is zero.
Solution 2 b: Using bitwise operator
1) Using temporary variable / Using extra space
2) Without using temporary variable / Without using extra space
a) Using arithmetic operators
b) Using bitwise operator
Solution 1: Using temporary variable
//SwapUsingExtraVariable.java
public class SwapUsingExtraVariable {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Values before swapping");
System.out.println("a= " +a + " b= "+b);
int temp = a;
a = b;
b = temp;
System.out.println("Values after swapping");
System.out.println("a= " +a + " b= "+b);
}
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
Solution 2 a: Using arithmetic operators
//SwapUsingArthematic.java
public class SwapUsingArthematic {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Values before swapping");
System.out.println("a= " +a + " b= "+b);
a = a + b;
b = a - b;
a = a - b;
// a = a * b;
// b = a / b;
// a = a / b;
System.out.println("Values after swapping");
System.out.println("a= " +a + " b= "+b);
}
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
We can use "*" & "/" operators also instead of "+" & "-". Check the above program lines 14, 15 and 16 for the reference. But problem with "/" operator is it gives java.lang.ArithmeticException: / by zero Exception for "b" value is zero.
Solution 2 b: Using bitwise operator
//SwapUsingBitWiseOperator.java
public class SwapUsingBitWiseOperator {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Values before swapping");
System.out.println("a= " +a + " b= "+b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("Values after swapping");
System.out.println("a= " +a + " b= "+b);
}
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
Sunday, June 8, 2014
Technical Interview Question 1
You have an array of numbers from 0 to N-1, one of the numbers is removed, and replaced with a number already in the array which makes a duplicate of that number. How can we detect this duplicate in time O(N).
For example an array of 6 integers - 0,1,2,3,4,5. one of the number i.e "3" removed and replaced with "2". now array would become 0,1,2,2,4,5
Solution :
// InterviewQuestion1.java
public class InterviewQuestion1 {
public static void main(String[] args) {
int[] testArray = { 0, 1, 2, 2, 4, 5 };
boolean[] testBool = new boolean[testArray.length];
for (int i = 0; i < testArray.length; i++) {
testBool[testArray[i]] = true;
}
System.out.print("Duplicate Number is : ");
for (int i = 0; i < testArray.length; i++) {
if (!testBool[i]) {
System.out.print(testArray[i]);
break;
}
}
}
}
// Output: Duplicate Number is : 2
Sample Code
// Hello World.java
public class HelloWorld{
public static void main(String[] args){
System.out.print("Hi");
}
}
Saturday, June 7, 2014
Java Program1
Write a Java Program to concatenate all characters at first and sum of numbers at last from the given string.
For Example:
Input String :: azch1234dhrk345
Output: azchdhrk22
Solutions :
1) Using java regex package
2) Using Character class
Solution 1:
For Example:
Input String :: azch1234dhrk345
Output: azchdhrk22
Solutions :
1) Using java regex package
2) Using Character class
Solution 1:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SumOfNumbersInString {
public static void main(String[] args) {
String myString = "azch1234dhrk345";
SumOfNumbersInString s = new SumOfNumbersInString();
System.out.print(s.getResultString(myString));
}
public String getResultString(String myString){
Pattern pattern = Pattern.compile("\\d");
Matcher match = pattern.matcher(myString);
int sum = 0, index = 0;
String otherString = "";
boolean matchFind = false;
while (match.find()) {
matchFind = true;
otherString += myString.substring(index, match.start());
sum += Integer.parseInt(match.group());
index = match.end();
}
if(index < myString.length()){
otherString += myString.substring(index);
}
if(matchFind){
return otherString + sum;
}
return myString;
}
}
// Output : azchdhrk22
Solution 2:
//SumOfNumbersInString2.java
public class SumOfNumbersInString2 {
public static void main(String[] args) {
String myString = "azch1234dhrk345";
SumOfNumbersInString2 s = new SumOfNumbersInString2();
System.out.print(s.getResultString(myString));
}
public String getResultString(String myString) {
StringBuffer sb = new StringBuffer();
int sum = 0;
// Iterate over the string from 0th index to length()-1 characters
// Check for the digit
// If it is a digit, add this value to sum
// If it is not digit, append to String Buffer Object
for (int i = 0; i < myString.length(); i++) {
char ch = myString.charAt(i);
if (Character.isDigit(ch)) {
sum += Character.getNumericValue(ch);
} else {
sb.append(ch);
}
}
return sb.toString() + sum;
}
}
// Output : azchdhrk22
Wednesday, June 4, 2014
String Concatenation Operator
String name = "Venkatesh";
int age = 5;
int salary = 6;
System.out.println(name + age + salary);
What is the Output?
Answer:-
Rule:
If either operand is a String, the + operator becomes a String concatenation operator. If both operands are numbers, the + operator is the addition operator.
Note: The operands are the things on the left or right side of the operator.
Example: the expression a+b --> here a & b are the operands and "+" is operator.
Finally the answer is : Venkatesh56
int age = 5;
int salary = 6;
System.out.println(name + age + salary);
What is the Output?
Answer:-
Rule:
If either operand is a String, the + operator becomes a String concatenation operator. If both operands are numbers, the + operator is the addition operator.
Note: The operands are the things on the left or right side of the operator.
Example: the expression a+b --> here a & b are the operands and "+" is operator.
Finally the answer is : Venkatesh56
Tuesday, June 3, 2014
Sort Month Names
1) Sorting months by natural sort order or alphabetical order or not chronological order.
2) Sorting months by Chronological order.
2) Sorting months by Chronological order.
Solution for Question 1 ::
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
// Natural Order : Month name by Lexicographic order
public class SortSample {
public static void main(String[] args) {
List<String> wordList = Arrays.asList( "Feb","Jul",Jan", "Apr","Dec", "Aug", "Oct","May","Sep","Nov", "Jun","Mar");
System.out.println(wordList);
Collections.sort(wordList);
System.out.println(wordList);
}
}
Solution for Question 2 ::
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class SortSample1 {
public static void main(String[] args) {
List<String> months = Arrays.asList( "Feb", "Jul", "Jan", "Apr", "Dec", "Aug", "Oct", "May", "Sep", "Nov", "Jun","Mar");
System.out.println(months);
final Comparator<String> dateCompare = new Comparator<String>() {
public int compare(String o1, String o2) {
SimpleDateFormat s = new SimpleDateFormat("MMM");
Date s1 = null;
Date s2 = null;
try {
s1 = s.parse(o1);
s2 = s.parse(o2);
} catch (ParseException e) {
e.printStackTrace();
}
return s1.compareTo(s2);
}
};
Collections.sort(months, dateCompare);
System.out.print(months);
}
}
Friday, May 30, 2014
CodingBat > roundSum
For this problem, we'll round an int value up to the next multiple of 10
if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round
down to the previous multiple of 10 if its rightmost digit is less than 5, so
12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded
values. To avoid code repetition, write a separate helper "public int round10(int
num) {" and call it 3 times. Write the helper entirely below and at the
same indent level as roundSum().
roundSum(16, 17, 18) → 60
roundSum(12, 13, 14) → 30
roundSum(6, 4, 4) → 10
Solution ::
public int roundSum(int a, int b, int c) {
return round10(a) + round10(b) + round10(c);
}
public int round10(int num) {
int remainder = num % 10;
num -= remainder;
if (remainder >= 5) {
num += 10;
}
return num;
}
CodingBat > firstLast6
Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more.
firstLast6({1, 2, 6}) → true
firstLast6({6, 1, 2, 3}) → true
firstLast6({13, 6, 1, 2, 3}) → false
Solution ::
Solution ::
public class FirstLast6 {
public static void main(String[] args) {
FirstLast6 fl = new FirstLast6();
int[] testArray = new int[] { 1, 2, 6 };
System.out.print(fl.firstLast6(testArray));
}
public boolean firstLast6(int[] nums) {
if (nums[0] == 6 || nums[nums.length - 1] == 6)
return true;
return false;
}
}
Subscribe to:
Posts (Atom)

