What is wrong with my code? NullPointerException - java

What is wrong with the below code? It will throw NullPointerException while execution time.
public class Test
{
public String method1()
{
return null;
}
public Integer method2()
{
return null;
}
public static void main(String args[])throws Exception
{
Test m1 = new Test();
Integer v1 = (m1.method1() == null) ? m1.method2() : Integer.parseInt(m1.method1());
}
}

The type of a a ? b : c is the type of the last value c. In this case it's an int. This means that even though b is being chosen it is being unboxed and then re-boxed into an Integer. As the value is null, this fails.
Here is a similar example which may help (or be more confusing)
Integer i = 1000;
// same as Integer j = Integer.valueOf(i == 1000 ? i.intValue() : 1000);
Integer j = i == 1000 ? i : 1000;
System.out.println(i == j);
Integer k = i == 1000 ? i : (Integer) 1000;
System.out.println(i == k);
prints
false
true
The reason the first result is false, is that expression has a type of int (the last argument) which means i is unboxed to be an int and reboxed so it can be assigned to the Integer. This results in a different object (There are command line args which would increase the cache size and change this) In the second example the type is Integer so it is not unboxed and the object is the same.

parseInt returns int. That makes the compiler to unbox m1.method2() but it is null so it throws:
Integer v1 = (m1.method1() == null) ? m1.method2() : (Integer)Integer.parseInt(m1.method1());

Related

Ternary If that includes a functions result

I was just wondering if there's a more efficient way to do something along the lines of this in Java.
Just going to use this dummy function as an example
static int getDivision(int number, int divider) {
if(divider == 0) { return -1; }
return (number / divider);
}
If I have a ternary operator that is checking the result of that function like the below
public static void main(String[] args) {
int result;
result = getDivision(2, 0);
System.out.println (
result == -1 ? "No" : result
);
}
I have to create a variable to store the result, otherwise I can do it like this
System.out.println (
getDivision(2, 0) == -1 ? "No" : getDivision(2, 0)
);
But I have to call the function twice which is even worse. Is it possible to use the ternary operator but include the result of a function in the conditions?
System.out.println (
getDivision(2, 0) == -1 ? "No" : /*returned result*/
);
Using Optional, you can represent a real result as well as indicate that no result is present:
static Optional<Integer> getDivision(int number, int divider) {
return divider == 0 ? Optional.empty() : Optional.of(number / divider);
}
Usage:
Optional<Integer> result = getDivision(2, 0);
System.out.println(result.map(String::valueOf).orElse("No"));
Or if you only want to further process the result when it is present:
result.ifPresent( value -> ...);
EDIT: the value -1 is also a valid outcome of some divisions, which works fine with the Optional as well, compared to the original approach:
Optional<Integer> result = getDivision(-5, 5);

Java method returns int that can't be compared to another int (Android Studio)

First off, these are ints, not Integers.
I want to get a variable from another class and compare it to a value, like so:
Log.v("xx", "" + boardAdap.getPieceNumber());
int pieceNumberInt = boardAdap.pieceNumber;
if (pieceNumberInt == 32) {
Log.v("xx", "int comparison worked");
}
int pieceNumberMethod = boardAdap.getPieceNumber();
if (pieceNumberMethod == 32) {
Log.v("xx", "method comparison worked");
}
So, I want to get the pieceNumber variable from the boardAdap class, and check if it is equal to 32. If it is, it prints the stuff in Log in the console.
The boardAdap method:
int pieceNumber;
int pieceNumberIncrement;
public int getPieceNumber() {
for (int i = 0; i < 64; i++) {
if (board.getPiece(Square.squareAt(i)).name() != "NONE") {
this.pieceNumberIncrement++;
}
}
this.pieceNumber = pieceNumberIncrement;
return pieceNumber;
}
This iterates through an enum called Square, and increments pieceNumberIncrement if the value is not "NONE".
However, when I run this, the output is:
32
int comparison worked
So, why does the second if condition fail, if getPieceNumber() returns an int? It also fails when I use an Integer wrapper, or convert pieceNumberMethod to a string and then to an Integer, and other methods.
Also, should I change getPieceNumber() to just update the pieceNumber instead, and reference only that?
Additionally, if pieceNumberMethod is used in a for loop like:
for (int i = 0; i < pieceNumberMethod; i++) {
}
The for loop will never stop.
Thanks!
You are basically calling getPieceNumber twice so in the second call the number changes.
int pieceNumberMethod = boardAdap.getPieceNumber();
Log.v("xx", "" + pieceNumberMethod);
int pieceNumberInt = boardAdap.pieceNumber;
if (pieceNumberInt == 32) {
Log.v("xx", "int comparison worked");
}
if (pieceNumberMethod == 32) {
Log.v("xx", "method comparison worked");
}
Try calling method once.Hope that works!
The problem is comparing the strings. You need equals("NONE")
String none = new String("NONE");
int count = 32;
System.out.println(count);
for (int i = 0; i < 64; i++) {
if (none != "NONE") {
count++;
}
}
System.out.println(count);
If you run this code it will print different values for "count" despite value of "none"

Why is post increment operator in a return statement act different from expected in Eclipse?

I see this post: In Java, how does a post increment operator act in a return statement?
And the conclusion is: a post increment/decrement happens immediately after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated.
I tried the sample code in the post like below in Eclipse:
class myCounter {
private int _ix = 1;
public int ixAdd() {
return _ix++ + giveMeZero();
}
public int giveMeZero()
{
System.out.println(_ix);
return 0;
}
}
public class mytest {
public static void main(String[] args) {
myCounter m = new myCounter();
System.out.println(m.ixAdd());
}
}
and the result is:
2
1
It shows that _ix is incremented to 2 in giveMeZero() as expected. But ixAdd() is still returning 1.
Why is this happening? Isn't it against what In Java, how does a post increment operator act in a return statement? is all about?
Thanks,
Remember that the post increment operator evaluates to the original value before the increment is performed.
This means that e.g.
int a = i++;
is similar to doing:
int a = i;
i = i + 1;
That is, a receives the original value of i and after that, i is incremented.
When used in a return statement, there's no difference, it evaluates to the value before the increment.
return _ix++ + giveMeZero();
would be similar to:
int temp = _ix;
_ix = _ix + 1;
return temp + giveMeZero();
Think about the compiler evaluating each part of that return statement on at a time:
return _ix++ + giveMeZero();
Is the same as:
int tmp1 = _ix++;
int tmp2 = giveMeZero();
return tmp1 + tmp2;
So by the time giveMeZero is evaluated, _ix has already been incremented.
It is because _ix++ + giveMeZero(); first return then add 1 to _ix.
if you do ++_ix then it is OK
Note: ++ if first occur it means that firs add one and then do the operation, if occur after then it means that first do that operation then add one

Specify a Java class literal programmatically (without hard coding it)? reflection?

Questions:
In the line
Object o = myC.getConstructor(short.class).newInstance(myC.cast(pPrim));
Is there a way avoid hard coding "short.class" and instead get a literal from pPrim?
I got the idea for using "short.class" from the answer in Create new object using reflection?
Shouldn't I be able to use "T o = ... (for a Byte or a Short, e.g.) instead of Object o = ...?
I think my method is nearly identical to the one found at the end of Class Literals as Runtime-Type Tokens.
Is what I want to do a case of reflection?
Background:
I'm studying the book OCA Java SE 7: Programmer 1 Study Guide by Finegan and Liguori in preparation for 1Z0-803.
So I'm practicing code a lot. While practicing, I wrote a class hoping to see what's going on
inside primitives when cast from a char. I listed the code below ... if you take a look please focus on the methods
byteToBinaryString, shortToBinaryString, and primitiveToBinaryString ... that's where my question arose.
Steps that got me to the question:
wrote byteToBinaryString
cloned byteToBinaryString to shortToBinaryString
thought, "I should be able to avoid this method repitition, maybe with generics"
cloned shortToBinaryString to primitiveToBinaryString and tried to convert to generic
began thinking this was a reflection thing also
got stuck with the class literal hard coding
Here's my code
import java.util.TreeMap;
import java.util.Set;
public class StackoverflowQuestion {
// I wrote this 1st
public static String byteToBinaryString(byte pByte) {
int primLength = 8;
int count = 0;
String s = "";
while ( count++ < primLength ) {
byte sm = (byte) (pByte & 0x01);
pByte >>= 1;
s = sm + s;
if ( count % 4 == 0 && count != primLength ) {
s = " " + s;
}
}
return s;
}
// Then I cloned byteToBinaryString to this and had the thought,
// I shouldn' have to repeat this
public static String shortToBinaryString(short pShort) {
int primLength = 16;
int count = 0;
String s = "";
while ( count++ < primLength ) {
short sm = (short) (pShort & 0x0001);
pShort >>= 1;
s = sm + s;
if ( count % 4 == 0 && count != primLength ) {
s = " " + s;
}
}
return s;
}
// So I cloned shortToBinaryString, modifidied to this and ...
public static <T extends Number> String primitiveToBinaryString(T pPrim) {
int primLength = 16;
int count = 0;
String className = pPrim.getClass().getName();
try {
Class<?> myC = Class.forName(className);
// ... got stuck here
Object o = myC.getConstructor(short.class).newInstance(myC.cast(pPrim));
System.out.println(pPrim + "<--pPrim.equals(o)-->" + pPrim.equals(o) + "<--" + o);
} catch ( Exception e ) {
System.out.println("Caught exception: " + e);
}
String s = "";
while ( count++ < primLength ) {
//T sm = new Class<T>(pPrim.intValue() & 0x0001);
//pPrim >>= 1;
//s = sm + s;
if ( count % 4 != 0 && count != primLength ) {
s = "-" + s;
}
}
return s;
}
public static void main ( String[] args ) {
// exercise byteToBinaryString
for ( int i = 0; i < 256; i++ ) {
char cByte = (char) i;
byte b1 = (byte) cByte;
System.out.printf( "char(%c): charValue(%05d): bin(%s): dec(%+6d)\n", cByte, (int) cByte, byteToBinaryString(b1), b1 );
}
// exercise shortToBinaryString
// please ignore my use of TreeMap, just figuring out how it works
TreeMap<Integer, String> charsTM = new TreeMap<Integer, String>();
charsTM.put(00000, "00000");
charsTM.put(00001, "00001");
charsTM.put(32766, "32766");
charsTM.put(32767, "32767");
charsTM.put(32768, "32768");
charsTM.put(32769, "32769");
charsTM.put(65535, "65535");
short s1 = 32767;
char ch1 = 32768;
Set<Integer> charKeys = charsTM.keySet();
// loop through the boundary values I selected to show what's going on in memory
for ( Integer i : charKeys ) {
ch1 = (char) i.intValue();
s1 = (short) ch1;
System.out.printf( "char(%c): charValue(%05d): bin(%s): dec(%+6d)\n", ch1, (int) ch1, shortToBinaryString(s1), s1 );
}
// exercise primitiveToBinaryString
primitiveToBinaryString( (byte) 127 );
primitiveToBinaryString( (short) 32767 );
primitiveToBinaryString( (int) 2147483647);
primitiveToBinaryString( 2147483648L);
primitiveToBinaryString( 2147483648F);
primitiveToBinaryString( 2147483648D);
}
}
A couple of things:
This could be cleaned up a little:
String className = pPrim.getClass().getName();
Class<?> myC = Class.forName(className);
//Can just do
Class<?> myC = pPrim.getClass();
Also, if you are looking for a single argument constructor that takes a primitive value you could do:
public Constructor<?> getPrimitiveSingleArgConstructor(Class<?> myC) {
for( Constructor<?> constructor : myC.getConstructors() ) {
if( constructor.getParameterTypes().length == 1 ) {
Class<?> paramType = constructor.getParameterTypes()[0];
if (paramType.isPrimitive()) {
return constructor;
}
}
}
}
Finally, if you are trying to convert a number to an binary string and you are only working with integer numbers (I'm assuming you are) you could always cast the number upwards to a long and convert that to a binary string.
long integralValue = pPrim.longValue();
As a matter of fact, you can obtain a class literal from a primitive value by forcing a boxing conversion, and then reflecting the static field TYPE (which is declared for any primitive wrapper).
short s = 0;
Object obj = s;
System.out.println(obj.getClass().getDeclaredField("TYPE").get(null));
Here obj.getClass()==Short.class, and Short.TYPE==short.class. The assignment obj=s is a boxing conversion (from short to Short), followed by a reference widening conversion (from Short to Object). It also works if you replace the assignment by an invocation to a method such as Object box(Object obj){return obj;} because both assignment conversions and method invocation conversions allow boxing conversions to take place.
However, all of this reflection does not provide any advantage with respect to hardcoding short.class, since you can't have generics on primitive types.

Java / JUnit - AssertionError testing a pre-defined polynomial

I have a Term class to define a polynomial:
public class Term
{
final private int coef;
final private int expo;
private static Term zero, unit;
static
{
try
{
zero = new Term(0, 0); // the number zero
unit = new Term(1, 0); // the number one
}
catch (Exception e)
{
// constructor will not throw an exception here anyway
}
}
/**
*
* #param c
* The coefficient of the new term
* #param e
* The exponent of the new term (must be non-negative)
* #throws NegativeExponent
*/
public Term(int c, int e) throws NegativeExponent
{
if (e < 0)
throw new NegativeExponent();
coef = c;
expo = (coef == 0) ? 1 : e;
}
final public static Term Zero = zero;
final public static Term Unit = unit;
public boolean isConstant()
{
boolean isConst = false;
if (this.expo == 0)
{
isConst = true;
}
return isConst;
}
}
And I have the JUnit test as follows:
/*
* const1 isConstant(zero) => true (0,0)
* const2 isConstant(unit) => true (1,0)
* const3 isConstant(0,5) => true
* const4 isConstant(5,1) => false
*/
#Test
public void const1() throws TError { assertTrue(Term.Zero.isConstant()); }
#Test
public void const2() throws TError { assertTrue(Term.Unit.isConstant()); }
#Test
public void const3() throws TError { assertTrue(new Term(0,5).isConstant()); }
#Test
public void const4() throws TError { assertFalse(new Term(5,1).isConstant()); }
Tests 2 and 4 pass as they should, but Tests 1 and 3 come up as failures and I cannot work out why, "Zero" is defining the polynomial as (0,0) and the other is defining it as (0,5). So by my thinking, the 1st one should give a green tick and the 3rd test should give a red cross as it has 5 as the exponent.
Any ideas?
Please review your constructor:
public Term(int c, int e) throws NegativeExponent{
if (e < 0) throw new NegativeExponent();
coef = c;
expo = (coef == 0) ? 1 : e;
}
When coef == 0, then exp is assigned with 1.
This makes zero as (0,1) not (0,0). this is the reason for test outcome as below:
const1 -> false as expo = 1-->failure as expecting true
const2 -> true as expo = 0 -->success as expecting true
const3 -> false as expo = 5.-->failure as expecting true
const4 -> false as expo = 1.-->success as expecting false
EDIT: To reverse fix your code to make the test cases pass, I think you may update your constructor as below:
public Term(int c, int e) throws NegativeExponent{
if (e < 0) throw new NegativeExponent();
coef = c;
expo = (c == 0 && e != 0) ? 0 : e;
}
Here, I have updated the constructor to set expo as 0, if coef is 0 as any expo for coef 0 is immaterial.
Yogendra covered why your first test fails. Your const3() fails (for me at least) because new Term(0, 5) has a expo of 5, which gets replaced with 1 b/c of the coef, but 1 is still not 0 so new Term(0, 5) is NOT constant.
Not that you asked, but I'll also give you some general Java pointers for the future...
1) Use all caps for static constants
public static final Term ZERO = new Term(0, 0);
public static final Term UNIT = new Term(1, 0);
this is just a convention that the Java community expects.
2) Give your test cases meaningful names. One powerful use of test cases is that they can double as documentation of your assumptions at the time. Rather than const1() which tells a fellow developer nothing, use a descriptive name like zeroShouldBeAConstant(). This tells the next person who looks at your code that Zero should be considered a constant in this system.
3) Whenever you are returning a boolean variable, consider just returning the statement. Compare the function below to yours and tell me which one is more readable:
public boolean isConstant()
{
return expo == 0;
}
It is less code and hopefully easier to read.
Good luck!

Categories

Resources