Defining method in java - java

Let's say, 5 is considered a good number. A method is to define to check a number is good or not. Parameter type int and return type is boolean. If argument is 5 it will return true and false otherwise.
See this code:
class Library{
boolean isGood(int num){
return num==5;
}
}
public class String_handling {
public static void main(String[] args) {
int num=8;
System.out.println(new Library().isGood(num));
}
}
I know this code is okay.
But I want to define a method such that I can invoke in this way:
System.out.println(num.isGood());
As work on string like this:
MyString.contains("xy");
MyString.substring(0,4);
Is there any way? Give an example.

Since int is a primitive, the only way you can to that, is to make your own class MyInteger and add your method isGood(), like so
public class MyInteger{
private int num;
public MyInteger(int num){
this.num = num;
}
public boolean isGood(int num){
return this.num == num;
}
}

Related

Interface type in method, how do I access it?

I would like to define a custom Interface "Sorting" with a custom compareTo method
public class Testing implements Sorting{
public static void main(String [] args){
Testing x1 = new Testing (4);
Testing x2 = new Testing (5);
System.out.println(x1.compareTo(x2));
}
private final int x;
public Testing(int x){
this.x= x;
}
#Override
public int compareTo(Sorting s) {
if(this == s)
return 0;
if(this.x> ((Testing) s).x) return 1;
if(this.x<((Testing) s).x) return -1;
return 0;
}
}
I don't know how to access said compareTo method to compare the values, but I would like to be able to use this for ints, for Strings and all kinds of types that fit to Sorting.
Also, does
public class Testing<Integer> implements Sorting<Integer>{..}
help any bit if I use Testing for int only?
Edit: Thank you for the replies, I want to point out that I can't use Comparable.
To be more exact: I want to compare two objects, one is of Testing type, the other one is of type "Sorting" which is given to the method. How can I convert Sorting into the Testing type while still being able to compare those two?
Edit2: I think I managed it, I'll update the code above and then you can maybe understand what I'm struggling with, I still don't know why that exactly is possible, but it seems to work.
Use the Interfaces not the concrete types. That way you can mix different concrete types that implement the same interface.
Either you have to change to compareTo(V other) or you have to add something more to your interface like this:
public interface Sorting <V> {
V getValue();
int compareTo(Sorting<V> other);
}
public class Testing implements Sorting<Integer>{
public static void main(String [] args){
Sorting<Integer> x1 = new Testing (4);
Sorting<Integer> x2 = new Testing (5);
System.out.println(String.format("compareTo is %d", x1.compareTo(x2));
}
private final int value;
public Testing(int value){
this.value = value;
}
#Override
int getValue(){
return value;
}
#Override
public int compareTo(Sorting<Integer> other) {
int otherValue = other.getValue();
if(value > otherValue)
return 1;
else if(value < otherValue)
return -1;
return 0; // must be ==
}
}
Note that you don't really gain much by doing compareTo(Sorting<Integer> other) as opposed to compareTo(Integer other) as the other's implementation isn't important, which is why Comparable does just that. You also won't be able to use a lambda now as your interface has 2 abstract methods, you can still use an anonymous class though.
int someInt = 12344;
x1.compareTo(new Sorting<Integer>() {
#Override int getValue(){ return someInt; }
#Override int compareTo(Sorting<Integer> other) { return 0; }// who cares isn't used
}

Java polymorphism downcasting [duplicate]

This question already has answers here:
why java polymorphism not work in my example
(3 answers)
Closed 7 years ago.
I've been struggle to understand something that I'm sure is very simple, yet I'm newbie in java so I'm asking you guys:
public class A
{
public int num;
/**
* Constructor for objects of class A
*/
public A(){
num = 222;
}
public A(int n){
num = n;
}
public int getNum(){
return num;
}
public boolean f(A a){
return num == a.num*2;
}
}
public class B extends A
{
public int num;
public B(int n)
{
num = n;
}
public boolean f(B b){
return num == b.num;
}
}
public class Tester
{
public static void main(String[]args){
A a = new B(14);
System.out.print(a.num);
}
}
The output of this is: 222.
My question is why is 222 and not 14?
I did put constructor inside B that gets int, and I put that int(14) in a b constructor. So why do I get the result as if I used empty A contractor?
Can anyone please explain me the logic of this?
Thanks!
because you have two variables num and as you upcasting your object to A you are using variable from class A which holds only default value

Implementing Static Methods In A Class

From a book I'm going through:
"Design a class name MyInteger. The class contains:
...blah, blah, blah...
The methods isEven(), isOdd(), and isPrime() that return true if the value in this object is even, odd, or prime, respectively.
The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the specified value is even, odd, or prime, respectively.
The static methods isEven(MyInteger), isOdd(MyInteger), isPrime(MyInteger), that return true if the specified value is even, odd, or prime, respectively."
Here's what I've got so far. The top is easy to implement with object.isEven()...
The second, I assume this is just to display results without actually setting the value and changing the object? So I could just do object.isEven(2)?
The last one... that's throwing me off a lot. I have no idea. =/ Please help me out. Thanks in advance.
To clarify:
1.
public boolean isEven(){
// code
}
MyInteger object = new MyIntger(50);
object.isEven();
2.
public boolean isEven(int num){
// code
}
MyInteger.isEven(50)???
3.
public boolean isEven(int MyInteger)???
???
class MyInteger {
int number;
// CONSTRUCTOR
public MyInteger(int a) {
number = a;
}
public int getNumber() {
return number;
}
static boolean isEven(MyInteger myint) {
if (myint.getNumber() % 2 == 0)
return true;
else
return false;
}
}
Now the main class:
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyInteger myInteger=new MyInteger(10);
boolean result=MyInteger.isEven(myInteger);
if(result==true)
System.out.println("true result");
else
System.out.println("false result");
}
}
This seems to be the one that's confusing
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
You use use an instance of MyInteger to pass as an argument. Another way to pass MyInteger as an argument is:
MyInteger num = new MyInteger(5);
boolean odd2 = MyInteger.isOdd(num); // static call
class MyInteger{
int num;
public MyIntger(int num){
this.num = num;
}
// Method 1
public static boolean isOdd(int num){
...
}
// Method 2
public boolean isOdd(){
...
}
// Method 3
public static boolean isOdd(MyInteger num){
...
}
}
public class TestMyInteger{
public static void main(String[] args){
// Method 1 call
boolean odd1 = MyIntger.isOdd(5); // static call
// Method 3 call
boolean odd2 = MyInteger.isOdd(new MyInteger(5)); // static call
// Method 2 call
MyIntger num = new MyIntger(5); // create instance
boolean odd3 = num.isOdd(); // instance call
System.out.println(odd1);
System.out.println(odd2);
System.out.println(odd3);
}
}
For second one, the method is belong to the class. But not the created object.
If Your code like this :
MyInteger myInteger = new MyInteger(100);
You can call the method by this
MyInteger.isEven(50);
or
myInteger.isEven(50);
It is not related to 100 which set in object.
Consider this as a pointer, and then you might want to look at this question.
public class MyInteger {
private int value;
public MyInteger(int value) {
super();
this.value = value;
}
public static boolean isPrime(int value) {
// I would increment counter then test if the result of value modulo counter
// (that is if value % counter != 0) until counter >= square_root(value).
// Then the value is prime, otherwise
return false;
}
public static boolean isEven(int value) {
return (value & 1) == 0;
}
public static boolean isEven(MyInteger m) {
return isEven(m.value);
}
public static boolean isPrime(MyInteger m) {
return isPrime(m.value);
}
public static boolean isOdd(int value) {
return !isEven(value);
}
public static boolean isOdd(MyInteger m) {
return isOdd(m.value);
}
public boolean isEven() {
return isEven(this.value);
}
public boolean isOdd() {
return isOdd(this.value);
}
public boolean isPrime() {
return isPrime(value);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
You would be performing actions upon the MyInteger object rather than just a straight int.
Let's say your private variables and constructor look like this (we don't know exactly because it isn't posted):
private int myInt;
public MyInteger(int thisInt) {
myInt = thisInt;
}
You will need to implement an accessor method that returns the value of myInt within an instance of the MyInteger class and then use this accessor method in your static method to perform the operation.
So as an accessor method:
public int getInt()
{
return myInt;
}
And then your static method would reference this method in the same way you would in another program. Note that you have to specify the use of the MyInteger object even within the class:
public static boolean isEven(MyInteger myInteger)
{
//Code here
}
In terms of calling the static method, it would look something like this:
MyInteger myInteger = new MyInteger(50);
MyInteger.isEven(myInteger);
Here, you are referencing an instance of the MyInteger object (myInteger) rather than the primitive int, but because isEven isn't directly connected to a specific object, you have to tell your code where to find the isEven() method, the MyInteger class.

How to determine the primitive type of a primitive variable?

Is there a "typeof" like function in Java that returns the type of a primitive data type (PDT) variable or an expression of operands PDTs?
instanceof seems to work for class types only.
Try the following:
int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());
It will print:
java.lang.Integer
java.lang.Float
As for instanceof, you could use its dynamic counterpart Class#isInstance:
Integer.class.isInstance(20); // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false
There's an easy way that doesn't necessitate the implicit boxing, so you won't get confused between primitives and their wrappers. You can't use isInstance for primitive types -- e.g. calling Integer.TYPE.isInstance(5) (Integer.TYPE is equivalent to int.class) will return false as 5 is autoboxed into an Integer before hand.
The easiest way to get what you want (note - it's technically done at compile-time for primitives, but it still requires evaluation of the argument) is via overloading. See my ideone paste.
...
public static Class<Integer> typeof(final int expr) {
return Integer.TYPE;
}
public static Class<Long> typeof(final long expr) {
return Long.TYPE;
}
...
This can be used as follows, for example:
System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */
This relies on the compiler's ability to determine the type of the expression and pick the right overload.
You can use the following class.
class TypeResolver
{
public static String Long = "long";
public static String Int = "int";
public static String Float = "float";
public static String Double = "double";
public static String Char = "char";
public static String Boolean = "boolean";
public static String Short = "short";
public static String Byte = "byte";
public static void main(String[] args)
{
//all true
TypeResolver resolver = new TypeResolver();
System.out.println(resolver.getType(1) == TypeResolver.Int);
System.out.println(resolver.getType(1f) == TypeResolver.Float);
System.out.println(resolver.getType(1.0) == TypeResolver.Double);
System.out.println(resolver.getType('a') == TypeResolver.Char);
System.out.println(resolver.getType((short) 1) == TypeResolver.Short);
System.out.println(resolver.getType((long) 1000) == TypeResolver.Long);
System.out.println(resolver.getType(false) == TypeResolver.Boolean);
System.out.println(resolver.getType((byte) 2) == TypeResolver.Byte);
}
public String getType(int x)
{
return TypeResolver.Int;
}
public String getType(byte x)
{
return TypeResolver.Byte;
}
public String getType(float x)
{
return TypeResolver.Float;
}
public String getType(double x)
{
return TypeResolver.Double;
}
public String getType(boolean x)
{
return TypeResolver.Boolean;
}
public String getType(short x)
{
return TypeResolver.Short;
}
public String getType(long x)
{
return TypeResolver.Long;
}
public String getType(char x)
{
return TypeResolver.Char;
}
}
There are two ways that you can use to determine the type of the Primitive type.
package com.company;
public class Testing {
public static void main(String[] args) {
int x;
x=0;
// the first method
System.out.println(((Object)x).getClass().getName());
if (((Object)x).getClass().getName()=="java.lang.Integer")
System.out.println("i am int");
// the second method it will either return true or false
System.out.println(Integer.class.isInstance(x));
}
}

Java 'this' keyword

I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}

Categories

Resources