19 lut 2010

inicjalizacja


@Test
public void testInicjalizacji(){
Init it = new Init();

}

public class Init {

static String ss1;
String sm1;
String sm2;

static {
ss1=new String("'=ok");
prn("Klauzula static");
}
{
sm1=new String("ok");
sm2=new String ("ok");
prn("Klauzula instancyjna{}");
}

public Init() {
prn("Konstruktor");
}
}


Wynik:

Klauzula static
Klauzula instancyjna{}
Konstruktor

Przeciążanie metod


@Test
public void testPrzeciazanieMetod(){

f(5); //int
f(3/2); //int

short s=12;
f(s); //short
f(s-1); //int
f(1-1.0f); //float
f(s-1.0f); //float

byte b=10;
f(b/2); //int
f(b*b); //int
}

public void f(float x){ prn("float");}
public void f(byte x){ prn("byte"); }
public void f(short x){prn("short");}
public void f(int x){prn("int");}

Działania arytmetyczne


@Test
public void testDzialan(){

int x=-3%2;
assertEquals(-1,x ); //pass
x=-3/2;
assertEquals(-1, x); //pass

float y=1.1f;
y++;
assertTrue(y==2.1f); //pass

int i=1;
float f=i; //automatyczna promocja

f=3/2;
prn(f); //1.0
assertTrue(f==1); //pass

x=-1<<1; //przesunięcie ze znakiem
assertTrue(x==-2); //pass

x=4>>>1; //przesuniecie w lewo bez zbaku
assertEquals(x,2); //pass


}

Try,catch,finally


@Test
public void testTry(){

//!try{ } //musi być catch or finally
//! catch(Exception e){ } //musi być try
//!finally{} musi być try przed

try{ }finally{} //ok
try{}catch(Exception e){} //ok
}

18 lut 2010

ArrayList []


import java.util.ArrayList;

public class Test {
public static void main(String[] args) {
ArrayList array = new ArrayList();
array[0]="Hello world";
System.out.println(array[0]);
}
}


Nie ma operatora [] w listach!!

Static


// A.java
public class A {
private final int a = 10;
public static String b = "ClassA";
protected long c;
}

// B.java
public class B extends A {
public static String b = "ClassB";
private int d = 1;

public static void test() {
...
}
}




Z metod statycznych ma się tylko dostęp do zmiennych statycznych!

Pytanie: Do jakich zmiennych mam dostęp w B.test() ??

Cast


@Test
public void testCastowania(){

float _45f=45.0f;
char $='\u0000';
//!$=$*$; //promowane do int!!
$=(char)($*$); //poprawnie
//! $=-$; także int

//_45f=_45f/3;
//assertTrue(_45f==15); //pass

//porównanie inta z floatem

int _45i=45;

assertTrue(_45f==_45i);//pass
assertTrue(_45i==_45f);//pass

//inne promowania
long _45l=_45i; //autmoatyczne promowanie

// możliwa utrata informacji ->
//błąd kompilacji
//!_45i=_45l;

_45i=(int)_45l; //poprawnie!

float a12=(float)1/3;
prn(a12); //0.33333
int jestemIntem=(int)a12;
prn(jestemIntem); //0
//a12=1.1; //daje daoubla
a12=1.6f; //ok
jestemIntem=(int)a12;
prn(jestemIntem); //1 (zaokragla w dół)

}