Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. 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 - For Loop

for(int i = 1; i < 6; i++) {
    System.out.println(i);
}

Will produce:

1
2
3
4
5


Enhanced for loop:

List<Integer> list = new ArrayList();

    list.add(1);
    list.add(2);
    list.add(3);
        
    for (Integer i : list) {
       System.out.println(i);
    }


Will produce:

1
2
3

Java - List, ArrayList

List list = new ArrayList();

// add object to the list
String s = "Hello World!";
list.add(s);

Java - Convert Date to String

String stringDate = "";
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Date date = new Date();

stringDate = dateFormat.format(date);

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 - What is Java?

Java is a object oriented programming language developed by Sun Microsystems. It is platform independent which means it can run in almost any kind of computer with Java Runtime Environment (JRE) installed.

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);

MySQL - INSERT INTO

"users" table:

user_id user_name

INSERT INTO users (user_id, user_name) 
VALUES("1", "Jimmy McNulty");
Result:

user_id user_name
1 Jimmy McNulty

MySQL - SELECT

"users" table:

user_id name
1 John Doe
2 Jimmy McNulty

SELECT name FROM users;

Result:

name
John Doe
Jimmy McNulty