Lecture1 Intro Java Part1
Lecture1 Intro Java Part1
Methods
Lecture 1
Lectures Overview
Object-oriented languages:
- Java
- C#
Next 3 or 4 lectures:
- Lecture 1 and 1/2 Lecture 2: Java basics
- 1/2Lecture 2 and Lecture 3: C# basics
Java References
Java Technology
Java language
Variables
Declaration:
type name_var1[=expr1][, name_var2[=expr2]];
Nr. byte
Values
Default value
boolean
true, false
false
byte
-128 +127
(byte)0
short
-215 215-1
(short)0
int
-231 231-1
long
-263 263-1
0L
float
IEEE754
0.0f
double
IEEE754
0.0d
Java Language
Examples:
boolean gasit=true;
int numar=34, suma;
float eroare=0.45;
char litera=c;
litera=f;
litera=litera+1;
Java Comments
1. // entire line
2. /* multiple
lines */
3. /** used by documentation Javadoc tool
multiple
lines*/
/*
//
//
*/
OK!!
NOT OK!
Java Constants
final type name [=value];
Examples:
a) final
int MAX=100;
b) final
int MAX;
MAX=100;
MAX=150; //error
Array
Array with one dimension
type[] name;
type name[];
Array allocation:
array_name=new type[dim]; //memory allocation
//index
0 dim-1
Examples:
float[] vec;
vec=new float[10];
int[] sir=new int[3];
float tmp[];
tmp=vec;
//lung=5;
sir[0]=sir.length;
sir.length=2;
//error
int[] y;
int lung_y=y.length;
//lung_t=0;
Creation:
name=new type[dim1][dim2][dimn];
Accessing an element:
name[index1][index2][indexn];
Examples:
int[][] a;
a=new int[5][5];
a[0][0]=2;
int x=a[2][2];
//x=?
//x=?
int y=a[2].length;
//y=?
Declaration+creation+initialization:
char[][] lit={{a},{b}};
int[][] b={{1,2},
{2,5,8},
{1}};
double[][] mat=new double[][]{{1.3, 0.5}, {2.3, 4.5}};
//concatenating strings
//t=?, s=?
t[0]=A;
char c=t.charAt(0);
method length(): int lun=s.length();
t.equals(s)
/*Returns true if and only if the argument is a String object that
represents the same sequence of characters as this object. */
compareTo(): int rez=t.compareTo(s)
/*Compares two strings lexicographically. Returns an integer indicating
whether this string is greater than (result is > 0), equal to (result is =
0), or less than (result is < 0) the argument.*/
Operators
arihtmetic:
+, -, *, /, %
relational: >,
increment/decrement:
++, --
assignment:
conditional:
bitwise:
shift
- conditional
ternary operator:
?:
Operator precedence
Operators
Precedence (higher precedence on top, the same precedence on the same line)
1. Postfix
expr++ expr--
2. Unari
3.
* / %
4.
+ -
5.
6.
7.
== !=
8.
&
9.
10.
11.
&&
12.
||
13.
? :
Statements
Sequential Composition:
{
instr1;
instr2;
}
Conditional:
if (logica_expr)
instr;
if (logical_expr)
instr1;
else
instr2;
true
or
false.
Loop Statements
While statement:
while(logical_expr)
instr
do-while statement:
do
instr
while(logical_expr);
Loop Statement
FOR statement:
for(initialization;termination; step)
instr
termination, step
are mandatory
//?
Return statement:
return;
return value;
Continue statement
- skips the current iteration of a loop statement
- stops the execution of the loop instructions and forces
the re-evaluation of the loop termination condition
int[] x= { 2, 8, 3, 5, 12, 8, 62};
int elem = 8;
int nrApar=0;
for (int i = 0; i < x.length; i++) {
if (x[i] != elem)
continue;
nrApar++;
}
Switch statement
switch(integral-selector) {
case integral-value1 : statement;
case integral-value2 : statement;
case integral-value3 : statement;
case integral-value4 : statement;
case integral-value5 : statement;
// ...
default: statement;
}
[break;]
[break;]
[break;]
[break;]
[break;]
Switch example
switch (luna) {
case
case
case
case
case
case
case
case
case
case
case
case
1:
3:
5:
7:
8:
10:
12: nrZile = 31; break;
4:
6:
9:
11: nrZile = 30; break;
2: if ( anBisect(an) )
nrZile = 29;
else
nrZile = 28;
break;
default:
System.out.println(Luna invalida");
Compilation:
javac Test.java
Execution:
java Test
java Test ana 1 2 3
!!! You can use int value=Integer.parseInt(args[i]) in order to
transform a string value into an int value.
Encapsulation(hiding)
data (state)
Operations (behaviour)
Class Declaration/Definition:
//ClassName.java
[public] [final] class ClassName{
[data (fields) declaration]
[methods declaration and implementation]
}
1.
2.
3.
A class defined using public modifier it is saved into a file with the class
name ClassName.java.
A file .java may contain multiple class definitions, but only one can be public.
Java vs. C++:
Examples:
//Persoana.java
public class Persoana{
//...
}
// Complex.java
class Rational{
//...
}
class Natural{
//...
}
public class Complex{
//...
}
}
access_modifier can be public, protected, private.
1.
2.
3.
Examples:
//Persoana.java
public class Persoana{
private String nume;
private int varsta;
//...
}
//Punct.java
public class Punct{
private double x;
private double y;
//...
}
Initializing fields
At declaration-site:
private double x=0;
in constructor.
Any field that is not explicitly initialized will take the default value of
its type.
Constructors
The constructor body is executed after the object memory space is allocated in
order to initialize that space.
[...] class ClassName{
[access_modifier] ClassName([list_formal_parameters]){
//body
}
}
acces_modifier {public, protected, private}
list_formal_parameters takes the following form:
Type1 name1[, Type2 name2[,...]]
The constructor has the same name as the class name (case sensitive).
2. The constructor does not have a return type.
3. For a class without any declared constructor, the compiler generates an
implicit public constructor (without parameters).
1.
Overloading Constructors
A class can have many constructors, but they must have different signatures. .
//Complex.java
public class Complex{
private double real, imag;
public Complex(){
real=0;
imag=0;
}
//implicit constructor
this
The call of another constructor must be the first instruction in the caller constructor.
The callee constructor cannot be called twice.
It is not possible to call two different constructors.
A constructor cannot be called from a method.
//Punct.java
public class Punct{
private int x, y;
public Punct(){
this(0,0);
}
public Punct(int x, int y){
this.x=x;
this.y=y;
}
public void muta(int dx, int dy){
this(x+dx, y+dy);
}
}
//Erorrs?
Creating objects
Operator new:
Punct p=new Punct();
//the parentheses are compulsory
Complex c1=new Complex();
Complex c2=new Complex(2.3);
Complex c3=new Complex(1,1.5);
Complex cc; //cc=null, cc does not refer any object
cc=c3;
//c3 si cc refer to the same object in the memory
1.
2.
Defining methods
[...] class ClassName{
[access_modifier] Result_Type methodName([list_formal_param]){
//method body
}
}
access_modifier {public, protected, private}
list_formal_param takes the form Type1 name1[, Type2 name2[, ...]]
Result_Type poate can be any primitiv type, reference type, array, or void.
1.
2.
Defining methods
//Persoana.java
public class Persoana{
private byte varsta;
private String nume;
public Persoana(){
this(,0);
}
public Persoana(String nume, byte varsta){
this.nume=nume;
this.varsta=varsta;
}
public byte getVarsta(){
return varsta;
}
public void setNume(String nume){
this.nume=nume;
}
public boolean maiTanara(Persoana p){//...
}
}
Overloading methods
A class may contain multiple methods with the same name but with different signature.
A signature = return type and the list of the formal parameters
Objects as Parameters
Passing arguments
Primitive type arguments ( boolean, int, byte, long, double) are passed by value. Their
values are copied on the stack.
Arguments of reference type are passed by value. A reference to them is copied on the
stack, but their content (fields for objects, locations for array) can be modified if the
method has the rights to accces them.
1.
There is not any way to change the passing mode( like & in C++).
class Parametrii{
static void interschimba(int x, int y){
int tmp=x;
x=y;
y=tmp;
}
public static void main(String[] args) {
int x=2, y=4;
interschimba(x,y);
System.out.println("x="+x+" y="+y);
}
}
//?
Passing arguments
class B{
int val;
public B(int x){
this.val=x;
}
public String toString(){
return ""+val;
}
static void interschimba(B x, B y){
B tmp=x;
x=y;
y=tmp;
System.out.println("[Interschimba B] x="+x+" y="+y);
}
public static void main(String[] args) {
B bx=new B(2);
B by=new B(4);
System.out.println("bx="+bx+" by="+by);
interschimba(bx,by);
System.out.println("bx="+bx+" by="+by);
//?
}
}
Passing arguments
class B{
int val;
public B(int x){
this.val=x;
}
public String toString(){
return ""+val;
}
static void interschimbaData(B x, B y){
int tmp=x.val;
x.val=y.val;
y.val=tmp;
System.out.println("[InterschimbaData] x="+x+" y="+y);
}
public static void main(String[] args) {
B bx=new B(2);
B by=new B(4);
System.out.println("bx="+bx+" by="+by);
interschimbaData(bx,by);
System.out.println("bx="+bx+" by="+by);
//?
}
}
Array of objects
Array of objects
static Complex suma(Complex[] t){
Complex suma=new Complex(0,0);
for(int i=0; i<t.length;i++)
suma.aduna(t[i]);
return suma;
}
public static void main(String[] args) {
Complex[] t=genereaza(3);
Complex cs=suma(t);
System.out.println("suma "+cs);
Complex[] t1=null;
genereaza(3,t1);
Complex cs1=suma(t1);
System.out.println("suma "+cs1);
modifica(t);
System.out.println("suma dupa modificare "+suma(t));
}
}
Static methods
Static methods
1.
A static method cannot use those fields (or call those methods) which are not
static. It can use or call only the static members.
Static fields
public class Natural{
private long val;
public static long MAX=232.... //2^63-1
//....
}
public class Produs {
private static long counter;
private final long id=counter++;
public String toString(){
return ""+id;
}
//....
Static fields are shared by all class instances. They are allocated only once in
the memory.
Static fields
Initialization:
At declaration site:
If a static field is not intialized, it will take the default value of its type:
private static long counter; //0