Showing posts with label java to. Show all posts
Showing posts with label java to. Show all posts

Java - Type Casting

double d = 99.9;
 
// Type cast double to int
int i = (int) d;

Java - How to compare Strings

String string1 = "5up";
String string2 = "5up";

// false
string1 == string2;

// true
string1.equals(string2);

Java - Interface

public interface Animal {
    
    public void makeASound();

}

public class Dog implements Animal {

    public void makeASound() {
        System.out.print("bark");
    }

    public static void main(String args[]){
        Dog dog = new Dog();

        dog.makeASound();
   }

}




Result:

bark

Java - Convert double to int

double d = 1;
int i = (int) d;


Java - Convert long to int

long l = 1;
int i = (int) l;



To do it safely:

public static int convertLongToInt(long l) {
    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            ("Invalid value for: " + l);
    }
    return (int) l;
}

Java - Convert String to Date

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String ddMMyyyy = "20130128";
Date date = null;

date = (Date) formatter.parse(ddMMyyyy);



Or

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dd_MM_yyyy = "2013-01-28";
Date date = null;

date = (Date) formatter.parse(dd_MM_yyyy);


Java - Convert String to int

int i = null;
String s = "12345";

i = Integer.parseInt(s);

Java - Convert int to String

int i = 3;
String s = "";

s = Integer.toString(i); 

or

s = String.valueOf(i);