4. Reading the following codes, and answer the questions. String s new String(\"
ID: 3571988 • Letter: 4
Question
4. Reading the following codes, and answer the questions. String s new String("abc"); String s1 "abc"; System out println(s s1) System.out.println(s s2); System out println(s1 s2); Q1: How many objects are created after the first three statements executed? What's the output of the program containing the above statements? String hello Thello": String heel "hel' String lo System out println(hello "hel" 11o); System.out.println(hello "hel' lo), Q2: What's the output of the program with above statements? Explain why. 5. (Binary to decimal Write a method that parses a binary number as a string into a decimal integer. The method header is as follows: public static int binaryToDecimal(String binaryString) For example, binary string 10001 is 17. So, binaryToDecimal("10001") returns 17. Note that Integer.parselnt(" 10001", 2) parses a binary string to a decimal value. Do not use this method in this exercise. program that prompts the user to enter a binary string and displays the corresponding decimal integer value.Explanation / Answer
public class Runner {
public static void main(String[] args) {
String s = new String("abc");
String s1="abc";
String s2 = new String("abc");
System.out.println(s==s1);
System.out.println(s==s2);
System.out.println(s1==s2);
}
}
sample output
false
false
false
Three objects are created
public class Runner {
public static void main(String[] args) {
String hello="hello";
String hel ="hel";
String lo ="lo";
System.out.println(hello=="hel" +"lo");
System.out.println(hello=="hel" +lo);
}
}
sample output
true
false
public class BinaryToDecimal
{
public static void main(String[] args)
{
String binaryString = "10001";
System.out.println(binaryToDecimal(binaryString));
// System.out.println(Integer.parseInt(binaryString, 2);
}
//10001
public static int binaryToDecimal(String binaryString)
{
int decimal = 0;
for(int i=0; i<binaryString.length() -1 ; i++)
{
if(binaryString.charAt(i) != 0)
{
decimal += Math.pow(2, i);
}
}
return decimal;
}
}
sample output
15
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.