You are on page 1of 119

:

Java

:
.: 0701181049
: . -

1. .
2. .
3. .
4. .
5. .
6. .
7. .
8. .
9. .
10. .
11. .
12.

1.

Java.
, , .
Java (
C C++). ,
.
, , -
.
Java - .
, .
- ,
( , ,
). ( , ..)
( , .).
Java
.
, , Java ( C#, PHP
C++).
, , ,
. ,
. Java,
!
,
Java, ,

.
3

2. .



. ()
. ,
.
.
, .
, .
.
.
, ,
, C.
, . Java, C++,
C#, VisualBasic, Python, Ruby, PHP .
Java. .
Java
Java Java
,
, Java.

classHelloJava{
publicstaticvoidmain(String[]arguments){
System.out.println("Hello, Java");
}
}
, ,
"Hello, Java" . ,
. -
,
.
Java ?
:
- ;
- main();
- main().


HelloJava. class,
. HelloJava.
main()
() main(),
. Java
main() :
publicstaticvoidmain(String[]arguments)
, public,
static void, main
5

public

static

String.

arguments, ,
. args argv.
,
, , ,
.
main()
,
.
System.out println(),
"Hello, Java".
Java .
main()
, .

Java !
, class, public, static
void , System.out.
, !
, Java
. Class class
System.out SYSTEM.OUT.
,
, , ..


, , , ,
.
.

classHelloJava{
publicstaticvoidmain(String[]arguments){
System.out.println("Hello, Java");
}
}
-
.
:
classHelloJava{
publicstaticvoidmain(String[]arguments){
System.out.println("Hello, Java");
}
}
:
classHelloJava{publicstaticvoid
System.out.println("Hello, Java");}}

main(String[]arguments){

:
class
HelloJava
{public
staticvoidmain(
String[
]arguments){
System.
out.println("Hello, Java");}
7

}

, - .


Java .
,
.java.
.
,
HelloJava.java.

Java
Java e -
. C C++,

Java

.java.
Java javac
, .class.
Java bytecode , .

Java :

abstract

continue

for

new

switch

assert

default

goto

package

synchronized

boolean

do

if

private

this

break

double

implements

protected

throw

byte

else

import

public

throws

case

enum

instanceof

return

transient

catch

extends

int

short

try

char

final

interface

static

void

class

finally

long

strictfp

volatile

const

float

native

super

while

. const goto. ,
.
. -
. 1.2 strictfp, 1.4
assert, 1.5 enum.
Java , , , ,
, , .


- Java
.

.
, Java.

, " " "
9

" (Garbage Collector).


,
.

10

3. .

?
,
. , ,
. , ,
, . ,
, ,
.
, .
, .
, ,
() .
.
.

,
.

:
- ;
- ( );
- (defaultvalue).

:
- byte, short, int, long;
11

- float double;
- boolean;
- char;
- Object;
- String.
- (byte,
short, int, long, float, double, boolean, char, Object String),
:

byte
short
int

0
0
0

long

0L

float
double

0.0f
0.0d

boolean false

-128
+127
-32768
+32767
-2147483648
+2147483647
+92233720368547758
92233720368547758
07
08
-3.4+38
+3.4+38
-1.7+308
+1.7+308
true
false
0
+65535

char
'\u0000'
Object null
String
null
byte, short, int, long, float, double, boolean char
, Java -
.
Object String ,
( ). ,
Java, ,
Java.

12


byte, short, int long.
, .
byte. 8- ,
, 2 8, .. 256
.
0. , , -128,
+127.
short. 16-
. byte -
.
0. , -32768,
- +32767.
, int. 32-
. ,
, .
0. , -2147483648,
+2147483647.
, , long.
64- 0L. L
, long ( int).
, long , -9223372036854775808,
+9223372036854775807.


,
,
.
13

byte centuries = 20;


short years = 2000;
int days = 730480;
long hours = 17531520;
System.out.println(centuries + " centuries is " + years +
" years, or " + days + " days, or " + hours + " hours.");
-
. byte, long.
.
20 centuries is 2000 years, or 730480 days, or 17531520 hours.

,
, float double.
,

.
32- float.
0.0f 0.0F ( ). "f"
, float (
double). 6 9
( ). ,
, -3.4+38, +3.4+38.
, , double.
64- 0.0d 0.0D.
15 17 . ,
, -1.7+308, +1.7+308.

14



:
float floatPI = 3.14f;
double doublePI = 3.14;


boolean. ,
true false. false.
- .

,
, ,
. ,
-:
int a = 1;
int b = 2;
boolean greaterAB = (a > b);
boolean equalA1 = (a == 1);
if (greaterAB) {
System.out.println("A > B");
} else {
System.out.println("A <= B");
}
System.out.println("greaterAB = " + greaterAB);
System.out.println("equalA1 = " + equalA1);
:
A <= B
greaterAB = false
equalA1 = true
int,
greaterAB.
15

equalA1. greaterAB true,


>B, B>A.

.
char. .
, -.

,
char, 'a', 'b' 'A'
:
char symbol = 'a';
System.out.println(
"The code of '" + symbol + "' is: " + (int) symbol);
symbol = 'b';
System.out.println(
"The code of '" + symbol + "' is: " + (int) symbol);
symbol = 'A';
System.out.println(
"The code of '" + symbol + "' is: " + (int) symbol);
:

The code of 'a' is: 97


The code of 'b' is: 98
The code of 'A' is: 65
()
.
String. null.
, ( ),
. 12 " ",
,
.

16


,
, :
String firstName = "Ivan";
String lastName = "Ivanov";
String fullName = firstName + " " + lastName;
System.out.println("Hello, " + firstName + "!");
System.out.println("Your full name is " +
fullName + ".");
:

Hello, Ivan!
Your full name is Ivan Ivanov.

, .
Object
.

,
, :
Object container = 5;
Object container2 = "Five";
System.out.println("The value of container is: " + container);
System.out.println("The value of container2 is: " + container2);
:
The value of container is: 5
The value of container2 is: Five.

17

4. .

?
,
. , ,
. , ,
, . ,
, ,
.
, .
, .
, ,
() .
.
.

,
. :
- ;
- ;
- .

:
- ;
- ( );

18

- ( ).


, :
- ;
- ( );
- , .
:
< ><> [= <>]

:
byte centuries = 20;
short years = 2000;
int days = 730480;
long hours = 17531520;
float floatPI = 3.141592653589793238f;
double doublePI = 3.141592653589793238;
boolean isEmpty = true;
char symbol = 'a';
String firstName = "Ivan";


. "=".
,
.

:
int firstValue = 5;
int secondValue;
19

int thirdValue;
secondValue = firstValue;
thirdValue = firstValue = 3;


Java 2 : .
(valuetypes)
.
, : byte, int, short, long, float,
double, char, boolean. 1, 2, 4 8 .
.
(reference types)
(. . heap),
. (
),
.
, .. . ()
null. ,
, .

(garbage collector), ,
.
, , -
.
, ,
, : Object, String, Integer, byte[]. ,
,
. , ,
, .
20


1. , byte, short, int long,
: 52130; -115; 4825932; 97; -10000.
2. float
double: 34.567839023; 12.345; 8923.1234857;
3456.091?
3. int 256
(256 100 16).
4. isMale boolean
.
5. String "Hello" "World".
Object.
,

).

Object. String
Object.

21

5. .

,
. Java
.
?
,
.
. .
, ,
.
, , (+, - , /,
*) , , .
Java
Java :
-

,
.


/ .


.
22


, :

-, +, *, /, %, ++, --

&&, ||, !, ^

&, |, ^, ~, <<, >>, >>>

==, !=, >, <, >=, <=

=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=,
>>>=

(type), instanceof

., new, (), [], ?:


, , :

()

(unary)

(binary)

(ternary)

-, , ,
,
.
(:?) - ( ).
Java ,
. +.
(int, long, float .),
.
23

, /
.

:

int z = 4 + 8;
System.out.println(z); // 12
String firstName = "Lachezar";
String lastName = "Bozhkov";
String fullName = firstName + " " + lastName;
System.out.println(fullName);

+
, .


+, -, * .
, .
/ (integer),
( ).
%. (increment)
++ , -(decrement) .
++ -- (
) ,
,

24

)
, .


:
int squarePerimeter = 17;
double squareSide = squarePerimeter / 4.0;
double squareArea = squareSide * squareSide;
System.out.println(squareSide); // 4.25
System.out.println(squareArea); // 18.0625
int a = 5;
int b = 4;
System.out.println(a + b);
System.out.println(a + b++);
System.out.println(a + b);

// 9
// 9
// 10

System.out.println(a + (++b)); // 11
System.out.println(a + b);

// 11

System.out.println(14 / a);

// 2

System.out.println(14 % a);

// 4


(true
false). (&&), (||),
(^) (!).
Java ,
:
x

!x

x && y

x || y

25

x^y

true

true

false

true

true

false

true

false

false

false

true

true

false

true

true

false

true

true

false
false
true
false
false
false
, , ""
, , .
"" , .
. ,
true ,
false. .
true,
true.
true, false.

.
:
boolean a = true;
boolean b = false;
System.out.println(a && b);

// false

System.out.println(a || b);

// true

System.out.println(!b);

// true

System.out.println(b || true);

// true

System.out.println((5>7) ^ (a==b)); // false


+ (String). ,

26

. String,
, String,
String.

, :
String first = "Star";
String second = "Craft";
System.out.println(first + second); // StarCraft
String output = first + second + " ";
int number = 2;
System.out.println(output + number);
// StarCraft 2
String
.
println(), .
.
output.
output 2 ( number)
.
String, .
( )
.
StringBuilder
StringBuffer ( )
.


,
.
27

.
. 55
00110111.
,
,
" " -5V,
" " +5V.
"
", ,

.
.
,
, .
true false ( ),
, 0 1 ().
, "" (&),
"" (|), (~) "" (^).

.
:
short a = 3;

// 0000 0011 = 3

short b = 5;

// 0000 0101 = 5

System.out.println( a | b); // 0000 0111 = 7


System.out.println( a & b); // 0000 0001 = 1
System.out.println( a ^ b); // 0000 0110 = 6

28

System.out.println(~a & b); // 0000 0100 = 4


System.out.println(a << 1); // 0000 0110 = 6
System.out.println(a << 2); // 0000 1100 = 12
System.out.println(a >> 1); // 0000 0001 = 1
a
b. ,
. , .
, , 1 a
b, 1 . ".
1 - , 1 -
. " , a b
. -
.


Java
. Java :
- - (>)
- - (<)
- - (>=)
- - (<=)
- (==)
- (!=)
( ),
(true false).

29

- , -
.

,
Java:
publicclass RelationalOperatorsDemo {
publicstaticvoid main(String args[]) {
int x = 10, y = 5;
System.out.println("x > y : " + (x > y)); // true
System.out.println("x < y : " + (x < y)); // false
System.out.println("x >= y : " + (x >= y)); // true
System.out.println("x <= y : " + (x <= y)); // false
System.out.println("x == y : " + (x == y)); // false
System.out.println("x != y : " + (x != y)); // true
}
}
, x y
10 5. ,
println() System.out,
x y >. true, x
- y. 5
5
x y.

"=" ( ).
, :

30

1 = 2;

, :
int x = 6;
String helloString = " .";
int y = x;
6 x.
helloString,
x y.
Java "=", "==".
.

.


?:
.
3 . "?" ,
":" . ( )
.
:
1 ? 2 : 3
1 true, 2.
1 false, 3.

31

.
true, ()
. , false,
() .

"?:":
int a = 6;
int b = 4;
System.out.println(a > b ? "a>b" : "b<=a"); // a>b

,
, ,
?:. Java :
- "."
.
- [] .
- ()
.
- (type)
.
- new
.
- instanceof
.

32


.
, ,
(, ,
). :
int r = (150-20) / 2 + 5;
double surface = Math.PI * r * r;
double perimeter = 2 * Math.PI * r;
System.out.println(r);
System.out.println(surface);
System.out.println(perimeter);
.
. ,
.
:
70
15393.804002589986
439.822971502571
,
,
(increment, decrement) .
:
int a = 5;
int b = ++a;
System.out.println(a); // 6
System.out.println(b); // 6

33

:
1. ,
.
2. ,
5 7 .
3. , 7
( ).

6. .

?
,

.
(- )
(- ).
, -. ,

.

. ,
.

.
,
. ,
- , .

34

,
, - . ,
-
.
?
, .
, -
, ,
.
, .
?
.
Windows :
Start -> (All) Programs -> Accessories -> Command Prompt
, ,
:

,
,
.

35


"Command Prompt" "shell" "
" ,
, ,
.
"shell" () ""
().
"", ,
.
- (CLI Command Line Interface)
( cmd.exe).
- (GUI Graphical User Interface)
( Windows Explorer).
, ,
,
,
.
, .
Windows . .
Windows (cmd.exe),
. dir,
:

36


,
.
Windows
() "Command Prompt" "MSDOS Prompt" ( - Windows).
:

dir

cd <directory name>
mkdir

<directory

name>
rmdir <directory name>

37

type <file name>


copy

<src

file><destination file>


Windows. :

-
- , "Standard I/O" e Unix .
,
.

, ,
.
- Java ,
.

38



,
" " " ".

-
.
,
() ,
-.
, ,
.
( Java System.in),
( Java System.out)
( Java
System.err).
-.
,
Java.

print() println()
,
(, ):
:
System.out.println("Hello, this is Java");
System.out.println(5);
System.out.println(3.14159265358979);

39

, System.out.println
,
println() PrintStream (
PrintStream API- Java).
print() println(), print()
, ,
. println() "print line",
" ". , print(),
.
, "" ,
.
, print println:
System.out.println("I love");
System.out.print("this ");
System.out.print("Book!");
:
I love
this Book!
, ,
. , println(),
"I love" .
40

print, ,
"this" "Book!" .

printf()

printf(). "Print Formatted".
"C",
( BCPL).
printf()
Java. printf()
,
, "
". printf()
Java:
printf(<formatted string>, <param1>, <param2>, <param3>, )
printf()
,
:
String str = "Hello, Java!";
System.out.print(str);
System.out.printf("%s", str);
:

41

, "Hello, Java!" . ,
.
,
. printf().
printf() . %s ,
str, %s. printf() System.out, .
. PrintStream.
:
String name = "Boris";
int age = 18;
String town = "Plovdiv";
System.out.printf(
"%s is %d years old from %s!\n", name, age, town);
:

printf() ,
. , ,
, (%s %d). %s
, ,
name. %d, ,
. %s,
(town). \n,
, .

42


, -
, - .
,
. "
" "" .
,
.
.
, Java, System.in.
:
- ;
- , .
System.in
, System - in.
InputStream. ()
, .
- System.in.read() .
System.in.read() ,
, . Java
,
.

STDIN

Java ,
,
JVM

STDOUT


System.in.read()
System.in.read()

System.out.println()
System.out.println()

STDERR

43


(STDIN) (STDOUT, STDERR) Java. STDERR
. :
System.err.println("This is error!");

.


.
PrintingLetter.java
publicclass PrintingLetter {

publicstaticvoid main(String[] args) {


Scanner input = new Scanner(System.in);

System.out.printf("Enter person name: ");


String person = input.nextLine();

System.out.printf("Enter book name: ");


String book = input.nextLine();

String from = "Authors Team";

System.out.printf(" Dear %s,%n", person);


System.out.printf("We are pleased to inform " +

44

"you that \"%2$s\" is the best Bulgarian book. \n" +


"The authors of the book wishes you good luck
%s!%n",
person, book);

System.out.println(" Yours,");
System.out.printf(" %s", from);
}
}
:

. ""

,

.
.

1. , int
.
2. , "r"
.
45

3. , , , ,
. , .
,
.
4. , (integer)
, , ,
5 0.

7. .

if if-else
if if-else ,
,
.
if
if , :
if ( ) {

46


}
: if-, .
,
. .
, : {}.
. ,
.
.
true false.
true,
. ,
false, .
if
if:
publicstaticvoid main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers.");
int firstNumber = input.nextInt();
int secondNumber = input.nextInt();
int biggerNumber = firstNumber;
if (secondNumber > firstNumber) {
biggerNumber = secondNumber;
}
System.out.printf("The bigger number is: %d%n", biggerNumber);
}

47

if
if-,
, ,
-. , ,
. -.
int a = 6;
if (a > 5)
System.out.println(" - 5.");
System.out.println(" !");
,
if,
.
{} if !
if-else
if-else , :
if ( ) {

} else {
else-
}
: if, ,
, else, else-. else .
( ).
true false.
48

, .
true, , else .
, false, else,
.
if-else
:
x = 3;
if (x > 3) {
System.out.println("x - 3");
} else {
System.out.println("x - 3");
}
: x>3,
: "x - 3", (else) : "x 3". , x=3,
else-. :
x - 3
if

if-, .
if if-else .
if if-else if else
. else -
if . else if
.
49

,
.

,
.
if
if :
Scanner input = new Scanner(System.in);
System.out.println(
"Please enter two numbers (on separate lines).");
int first = input.nextInt();
int second = input.nextInt();
if (first == second) {
System.out.println("These two numbers are equal.");
} else {
if (first > second) {
System.out.println("The first number is greater.");
} else {
System.out.println("The second number is greater.");
}
}
:
, ,
-. :
Please enter two numbers (on separate lines).
2

50

4
The second number is greater.

switch-case
switch
.

switch-case ?
switch
( ).
:
switch ( ) {
case --1: ; break;
case --2: ; break;
case --3: ; break;
case --4: ; break;
default: ;}
, .
switch
(). ,
( ). ,
default .

switch .
, case break,
switch.
switch , break . ,
51

case ,
,
case- ,
.
break case .
,
switch.
switch ,
default break. ,
default case ,
switch. default
break,
. , default
,
switch .
switch
switch
(,
). , int,
byte, char enum. , ,
, switch .
if
.

,
.
:
int number = 6;

52

switch (number) {
case 1:
case 4:
case 6:
case 8:
case 10: System.out.println(" !"); break;
case 2:
case 3:
case 5:
case 7: System.out.println(" !"); break;
default: System.out.println(" !");
}

case break ,
6,
case
. ,
case ,
break.
:

1. if-,
,
- .

53

2. , (+ -)
, .
3. , - ,
.
4. , -
5 .
5. . ,
, 0. :
- {-2, -1, 1}, -1 1 0.
- {3, 1, -7}, 0.
6. ,
[1..9] :
- 1 3, 10.
- 4 6, 100.
- 7 9, 1000.
- 0 9, .

8. .

""?

. (loop) ,
.
, :
54

- ;
- .
, , (infinite).
while
- while.
while (condition) {
statements;
}
Condition , true fasle.
loop condition.
Statements , .
.
while ,
true, ,
(pre-test loop). , while
:

Expression

false

true
Statement(s)

while
While .

55

while ,
0 9
:
int counter = 0;
while (counter < 10) {
System.out.printf("Number : %d%n", counter);
counter++;
}
:

,
.

1 N
while
1 N. N .
num sum 1. num ,
.
1, ,
,
56

1 N. Sum .
num.
num ( 1 N) "+"
.
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
int num = 1;
int sum = 1;
System.out.print("The sum 1");
while (num < n) {
num++;
sum += num;
System.out.printf("+%d", num);
}
System.out.printf(" = %d%n", sum);
:

break
break .
break,
,
, break .

57



while break.
.
n, ,
- n. n! :
- n! = 1*2*3.......(n-1)*n, n>1;
- 1! = 1;
- 0! = 1.
N! , - n:
- n! = (n-1)!n, 1! = 1.
, n.
factorial 1, n . While ,
, .
true. break, , n
1. n,
factorial, n 1.
: n*(n-1)*(n-2)**3*2, n=1
.
Scanner input = new Scanner(System.in);
int n = input.nextInt();
long factorial = 1;
while (true) {
if (n == 1) {
break;
}
factorial *= n;

58

n--;
}
System.out.println("n! = " + factorial);
10 , :
10
n! = 3628800

do-while
Do-while while ,
.
(post-test loop).
do-while:
do {
statements;
}
while (expression);
do-while :

59

do-while
Do-while , ,
, - .

n,
while , do-while.
.
1, 0. .
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
long factorial = 1;
do {
factorial *= n;
n--;
} while (n > 0);
System.out.println("n! = " + factorial);
n=7:
n=7
n! = 5040

for
For- - while do-while,
- - .
for- :

60

for (initialization; test; update) {


statements;
}
, ,
. for
. -
.
(infinite loop) for
:
for ( ; ; ) {
statements;
}
, .
, ,
break, .
for
For- :
for (int num = 0; ...; ...) {

, .
-. ""
.
for
For- :
for (int num = 0; num < 10; ...) {
}

61

, . true
, false
. loop condition (
).

for- ,
:
for (int num = 0; num < 10; num++) {
}
.
- .
For-
for-
. , . 1
, 10 :
for (int small=1, large=10; small<large; small++, large--) {
System.out.printf("%d %d\n", small, large);
}
.
:
1 10
29
38
47
56

62

continue
continue - ,
.
.
[1...n],
7. for-.
1,
[1...n]. i
(i <= n).
2, .
7. continue,
(
).
.
.
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int sum = 0;
for (int i = 1; i <= n; i += 2) {
if (i % 7 == 0) {
continue;
}
sum += i;
}
System.out.println("sum = " + sum);
n=26 :
26

63

sum = 141
for
5 Java
, .. foreach, for.
, .
"",
.
for-:
for (variable : collection) {
statements;
}

, - for-
- , .
, for- :
int[] numbers = {2, 3, 5, 7, 11, 13, 17, 19};
for (int i : numbers) {
System.out.printf("%d ", i);
}
System.out.println();

String[] towns = {"Sofia", "Plovdiv", "Varna", "Bourgas"};


for (String town: towns) {

64

System.out.printf("%s ", town);


}

for- .
( ) .
:
2 3 5 7 11 13 17 19
Sofia Plovdiv Varna Bourgas

.
- - .
.
for .
, ,

, false.
for ,
. 2 for
. , ,
.
for (initialization; test; update) {
for (initialization; test; update) {
statements;
}

65


: n
n , :
1
12
123
...
123...n
for-. ,
. ,
"1" (1 , 1 ). "1 2" (2 , 2
). , ,
, .
:
- 1 ( , )
=>col = 1;
- , .
=>col<= row;
- 1.
for- () 1 n ( )
for- () , 1
. ,
.
:
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int row = 1; row <= n; row++) {

66

for (int col = 1; col <= row; col++) {


System.out.print(col + " ");
}
System.out.println();
}
, , .
n=7:


, ,
.
ABCD, : A+B = C+D (
). for-
. - .
1, 0. ,
, - . .
for (int a = 1; a <= 9; a++) {
for (int b = 0; b <= 9; b++) {
for (int c = 0; c <= 9; c++) {
for (int d = 0; d <= 9; d++) {

67

if ((a + b) == (c + d)) {
System.out.printf("%d%d%d%d%n", a,
b, c, d);
}
}
}
}
}
( ):

1. , 1 N.
N .
2. , 1 N,
3 7. N .
3. ,
- - .
4. ,
( 52 : 4 13 ).
5. , N
N : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, ...

68

6. , N!/K! N K (1<K<N).

9. .

""?
.
, :

69

Element of
an array

array
Array of 5
elements

Element
index

0, 1, 2, ... N-1.
.
.
,
.

.
, -
.
, .

Java , .
.

Java :
int[] myArray;
myArray , (int[]) ..
. [] , ,
, .
, ,
(reference), null,
.
70

() new
Java new,
() :
int[] myArray = newint[6];
6 .
, (heap) 6
:
Heap

Stack
myArray
[I@42e816

, myArray
(0x42e816) ,
. (
. .heap).
.

.
,
. Java ,
(default initial value)>
0
( null false ).
, .
.
(array literal expression):

71

int[] myArray = {1, 2, 3, 4, 5, 6};


.

, .
,
.
.. .
,
- for .
:
myArray[index] = 100;
100 ,
index, index .
,
:
int[] myArray = newint[6];
myArray[1] = 1;
myArray[5] = 5;
,
:
Stack
myArray
[I@42e816

Heap

72


-, ..
0. 0, 1 ..
N , N-1.


Java
. ,
.
java.lang.ArrayIndexOutOfBoundsException. ,
.

.
for Java .
, , n
:
int n = input.nextInt();
int[] array = newint[n];
, .
. n
..
:
for (inti = 0; i < n; i++) {
array[i] = input.nextInt();
}

73



, .

, ,
. . ,
.
,
:
String[] array = { "one", "two", "three", "four" };
System.out.println(array);
,
( ).
:
[Ljava.lang.String;@42e816

for :
String[] array = { "one", "two", "three", "four" };
for (int index = 0; index < array.length; index++) {
System.out.printf("element[%d] = %s%n", index, array[index]);
}
for, array.length ,
System.out.printf,
. :
element[0] = one
element[1] = two
74

element[2] = three
element[3] = four
, - :
String[] array = { "one", "two", "three", "four" };
System.out.println(java.util.Arrays.toString(array));
,
, :
[one, two, three, four]

for
for
. ,
:
int[] array = newint[] {1, 2, 3, 4, 5};
for (int index = 0; index < array.length; index++) {
array[index] = 2 * array[index];
}
System.out.println(Arrays.toString(array));

for
, .
.. , for

. , .
:

75

for (int index = 0; index < array.length; index += 2) {


array[index] = array[index] * array[index];
}
,
.
.
, , for
, ,
. :
int[] array = newint[] {1, 2, 3, 4, 5};
System.out.print("Reversed: ");
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}

.

,
"". , ,
.
8 8 (8 8
).
" "? ""?
Java
. .
.

76

int[].
int[], int[], ..
:
int[][] twoDimentionalArray;
,
( ).
.

:
int[][][] threeDimentionalArray;
,
,
- .

.
:
int[][] intMatrix;
float[][] floatMatrix;
String[][][] strCube;
.
[].
new
, :
int[][] intMatrix = newint[3][4];
float[][] floatMatrix = newfloat[8][2];

77

String[][][] stringCube = new String[5][5][5];


intMatrix 3 int[]
3 4. ,
.
, :
0

0
. m n,
m*n .
,
.


.
:
int[][] matrix = {
{1, 2, 3, 4}, // row 0 values
{5, 6, 7, 8}, // row 1 values
}
2 4
.
, .. .
, .

78



() ,
.
( )
, . ,

, .
, :
int[][] myInts = { {1, 2, 3}, {91, 92, 93, 94}, {2001, 2002} };
, .
3 , . Java
,
:

79


,
.
:
int[][] matrix = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
};

matrix.length.
,
( ). i-
matrix[i].length.


:
int[][] matrix = {
{ 1, 2, 3, 4 }, // row 0 values
{ 5, 6, 7, 8 }, // row 1 values
};
for (introw = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
System.out.printf("%d ", matrix[row][col]);
}
System.out.println();
}

80

,
. ,
, ,
.
.
, ,
:
1234
5678

1. , 20

5. .
2. ,
.
3. , char
( ) -
.
4. ,
. : {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} {2, 2, 2}.
5. ,
. : {3, 2, 3, 4, 2, 2, 4} {2, 3, 4}.
6. , N K,
N . K ,
.

81

7. , ,
, ( ).
: {4, 3, 1, 4, 2, 5, 8}, S=11 {4, 2, 5}.
8. ,
.
. (4,4):

a)

1
2
3
4

5 9 13
6 10 14
7 11 15
8 12 16

c)

7 11 14 16
4 8 12 15
2 5 9 13
1 3 6 10

b)

1
2
3
4

1
2
d)*
3
4

8 9 16
7 10 15
6 11 14
5 12 13
12
13
14
5

11
16
15
6

10
9
8
7

9. , (n, m).
.
(3,3), .

10. .

?
() ,
.
. ,
,
.

82

,
. , -
. 0,
1, 2, 3, 4, 5, 6, 7, 8 9, . ( ,
-
, , ..
).
, . ,
, .
, 10 .
,
0 1.
.
, : -
, ? ,
,
(.. ) ,
.. . , ,
-
, (e =
2,718281828), .
, ,
.
, 2 3. , 3
- , .
, ,

.

83


, , ()
. ,

. 351 1
1, 1024 1000.
,
. A (p) = (a (n) a (n-1) ...a (0) ,a (1) a (-2) ...a (-k) )

A( p ) = amTm
m=n

T m m- .
T m =Pm, ,
k

A( p ) = am P m
m=n

, A (p)
(a (n) a (n-1) ...a (0) ) (a (-1) a (-2) ...a (-k) ), a
M={0,1,2,..., p-1}. , ,
-
( , -)
, . ,
(-) ,
, - .
2, 8, 10 16 -
,
0 15 :

0000

0001

1
84

0010

0011

0100

0101

0110

0111

1000

10

1001

11

1010

12

10

1011

13

11

1100

14

12

1101

15

13

1110

16

14

1111

17

15


, ,

.
, , . ,
,
. .
.
.

:

10
85

50

100

500

1000
,
,
:
1. , ,
- ,
. :
III=3, MMD=2500.
2. ,
, . :
IX=9, XML=1040, MXXIV=1024.


, ..
.
10. 10.
( )
(100=1), (101=10),
(102=100) .. ,
- .
. 95031,
:
95031 = (9x104) + (5x103) + (0x102) + (3x101) + (1x100)
, 95031 ,

86

. ,
. ,
. ,
,
.

, ..
. -
. ,
, 2.
. ,
0 1.
, ,
, ,
. 1110 (2)
. ,
, . ,
, (..
"").
, ,
2 .
(20=1),
(21=2),
(22=4) .. 8-, (27=128).
16-, (215=32768). 8
(0 1) 256 , 28=256.
16 65536 ,
216=65536.

87

.
148. : 1, 4 8,
:
10010100 (2)
148 = (1x27) + (1x24) + (1x22)
0, ,
1, .


,
.
,
, .
,
, .
11001 (2).
:
11001 (2) = 1x24+ 1x23+0x22 +0x21+1x20 =
= 16 (10) + 8 (10) + 1 (10) = 25 (10)
, 11001 (2) = 25 (10)
, 2 , ,
( ). ,
, ,
.
,
. -
.
88

( ).
,
. :
1001 (2) = ((1.2+0).2+0).2+1 = 2.2.2+1 = 9

,
.
. ,
.
148. ,
( 2). ,
( ),
. , . :
148:2=74 0;
74:2=37 0;
37:2=18 1;
18:2=9

0;

9:2=4

1;

4:2=2

0;

2:2=1

0;

1:2=0

1;

,
, , :
10010100

89

.. 148 (10) = 10010100 (2)



16,
16 ()
0 15 .
,
0 9 A F.
:
A=10, B=11, C=12, D=13, E=14, F=15
, D2,
1F2 F1, D1E .
160
- , 161 , 162 ..
. :
D1E (16) = *160 + 1*161 + D*162 = 14*1 + 1*16 + 13*256 = 3358 (10) .

16 . :
3358 / 16 = 209 + 14 ()
209 / 16 = 13 + 1 (1)
13 / 16 = 0 + 13 (D)
D1E (16) .

,
, (
). ,

90

.
,
. :
: 1110011110 (2) .
1.
: 0011 1001 1110.
2.
39E (16) .
1110011110 (2) = 39E (16) .


, .
(, )
.
.
,
. ,
, ,
.

. - , .
, 0 1.
8 ,
.
,
(2, 4 8),

91

. ,
.

, .
,
: .
. - 1

() .
.

1, 2, 4 8 .
, ,
. n
[0, 2n-1].
, a :

0 28-1

0 255

0 216-1

0 65 535

0 232-1

0 4 294 967 295

8
0 264-1
0 9 223 372 036 854 775 807
158,
10011110 (2) :
1. 1 :
1
2. 2 :

92


,
, -
. ,
1 , .
, :

-27 27-1

-128 127

-215 215-1

-32 768 32 767

31

31

-2 2 -1

-263 263-1

-2 147 483 648 2 147 483 647


-9 223 372 036 854 775 808

9 223 372 036 854 775 807


, ,
.
: [-2n-1, 2n-1-1].
, .
: - .
, .
:
3 00000011.
-3 10000011.
: ,
( ).
,
, .
93


.
, .
.. 2n
. :
-127 1 1111111,
1 0000000.
3 0 0000011, 0
1111100.
: ,
( ) . :
-127 1 0000001.
- : BCD (Binary Coded Decimal).
. ,
.
.. .

.

, -
.

.

, ,

.

94


, strictfp.
, .

,
decimal C#, money SQL Server number(10,2)
Oracle. Java .
(
), BigDecimal,
, - float
double. ,
:
import java.math.BigDecimal;

publicclass Precision {
publicstaticvoid main(String[] args) {
double sum = 0.0d;
BigDecimal bdValue = new BigDecimal("0.1");
BigDecimal bdSum = new BigDecimal("0.0");
for(int i=1; i<=10; i++) {
sum += 0.1d;
bdSum = bdSum.add(bdValue);
}
System.out.println("Double sum is: " + sum);
System.out.println("BigDecimal sum is: " + bdSum);
}
}

95

,
sum double
BigDecimal. :
Double sum is: 0.9999999999999999
BigDecimal sum is: 1.0

1. 151, 35, 43, 251 -0,41 .


2. 1111010110011110 (2)
.
3. 2A3E, FA, FFFF, 5A0E9
.
4. , .
5. , .
6.

11. .

96

""?
(method) , .
,
, . ,
.
. ,
, ,
.
:
publicstaticdouble getRectagnleArea(
double width, double height) {
double area = width * height;
return area;
}

?
, .
, , ,
.
- -
, ,
- - ,
.
, , , 20%
, , .

. , ,
97

, .
.

, ,
.
.

,
Java-.
() , ,
, .
.
,
, ,
, .

,
.

, ,
, , ,
"{" "}",
. , "
", ,

"{" "}". ,
( -).
98


"{" "}"
.
- main()
, ?
HelloJava.java
publicclass HelloJava {
publicstaticvoid main(String[] args) {
System.out.println("Hello Java!");
}
}


,
. :
[public] [static] <return_type><method_name>([<param_list>])
:
- <return_type>.
- <method_name>.
- <param_list>
.
, main()
HelloJava :
publicstaticvoid main(String[] args)

99

, void (.. ),
main, , ,
String[] args.
,
.

<return_type>,

<method_name> , <param_list>
"(" ")".
, ,
:
,
.
( "()"
). ,
.
"(" ")",
, .
, <return_type> , void, ,
. - ,
.


, ,
.
, , () ,
.
-, printLogo:

100

publicstaticvoid printLogo() {
System.out.println("Sun Microsystems");
System.out.println("www.sun.com");
}

, ,
, Sun:
- .
- camelCase, .. ,
, .
-
.
, , .
, Java Sun.
:
print
getName
playMusic
setUserName
, . , ,
, ,
, .

:
- .

101

- .
- camelCase.
-
- .


,
"{" "}", .
publicstatic<return_type><method_name>(<parameters_list>) {
}
, , .
,
.
, ,
:
publicstaticvoid printLogo() {
System.out.println("Sun Microsystems");
System.out.println("www.sun.com");
}
,
, :

.


, ,
, .
102

, , , ,
,
.
, ,
.


, ,
. ,
, .
, - ,
:
publicstaticvoid printMax(float number1, float number2) {
float max = number1;
if (number2 > number1) {
max = number2;
}
System.out.println("Maximal number: " + max);
}


, ,
,
:
float var1, var2;
,
.
103

, :
publicstaticvoid printMax(float var1, var2)
, :
publicstaticvoid printMax(float var1, float var2)


,
. , ,
, .
,
.
:
printSign(-5);
printSign(balance);
printMax(100, 200);


,

, .
- , ,
, (
" ").

104

, , ,
( "
").
, var1 var2,
:
publicstaticvoid printMax(float var1, float var2)
, -23.5 100,
:
printMax(100, -23.5);

- , Java
, .
, . , ,
.
,
.
, :
publicstaticvoid printNumber(int numberParam) {
numberParam = 5;
System.out.println("in printNumber() method, after the "
+

"modification,

numberParam);
}
main():
publicstaticvoid main(String[] args) {

105

numberParam

is:

"

int numberArg = 3;
printNumber(numberArg);
System.out.println("in the main() method number is: " +
numberArg);
}
3

numberArg,

numberParam. printNumber(),
numberParam 5.
numberArg, ,
numberParam . ,
printNumber() 5. ,
printNumber(), main()
numberArg , .
:
in printNumber() method, after the modification numberParam is:5
in the main() method number is: 3


( ) ,
( ), .
, "". ,
, ()
( ).
.
( ) :

106

arrArg: int[]
[I@e48e1b

variable

object

, ,
. . ,
, , , ,
. ( )?
?
- , :
modifyArr(),
, 5
, :
publicstaticvoid modifyArr(int[] arrParam) {
arrParam[0] = 5;

System.out.print("In modifyArr() the param is: ");


System.out.println(Arrays.toString(arrParam));
}
, main(),
modifyArr():
publicstaticvoid main(String[] args) {
int[] arrArg = newint[] { 1, 2, 3 };
System.out.print("Before modifyArr() the argument is: ");
System.out.println(Arrays.toString(arrArg));
modifyArr(arrArg);

107

System.out.print("After modifyArr() the argument is: ");


System.out.println(Arrays.toString(arrArg));
}
? :
Before modifyArr() the argument is: [1, 2, 3]
In modifyArr() the param is: [5, 2, 3]
After modifyArr() the argument is: [5, 2, 3]
, modifyArr(),
arrArg , [1,2,3], [5,2,3].
?
, ,
,
, .

,
, .

(var-args)
, ,
, , ,
, ,
.
,
, , ,
, .
, -, ,
.
108

, double[],
:
publicstaticvoid printTotalAmountForBooks(double[] prices) {
double totalAmount = 0;

for (double singleBookPrice : prices) {


totalAmount += singleBookPrice;
}
System.out.println("The total amount of all books is: " +
totalAmount);
}
, , ,
double
.
Java 5.0, ,
,
, ,
, , .
, , ,
:
double[] prices = newdouble[] { 3, 2.5 };
printTotalAmountForBooks(prices);
,
:
printTotalAmountForBooks(3, 2.5);
printTotalAmountForBooks(3, 5.1, 10, 4.5);
109


, , (var-args).

:
publicstatic<return_type><method_name>(<parameters_list>)
, , ,
<return type> void. , ,
void, (int,
float, double, ) ( String ),
, .
, , ,
, .
:
publicstaticdouble calcSquareSurface(double sideLength)
, double.

, ,
Java ,
. , ,
.

,
:
String companyLogo = getCompanyLogo();

110


, ,
.
,
:
float totalPrice = getSinglePrice() * quantity;

,
:
System.out.println(getCompanyLogo());
, getCompanyLogo(),
println(). getCompanyLogo()
, , "Sun Microsystems". Java
"" , ,
, :
System.out.println("Sun Microsystems");

-, ,
int, String, .. ,
void, ,
.
return
, ,
return, :
public static <return_type><method_name>(<parameters_list>) {

111

return <methods_result>;
}
<methods_result>, <return_type>. :
publicstaticint multiply(int number1, int number2) {
int result = number1 * number2;
return result;
}
, , return,
result.

, ,
( "What time is it?"). ,
, .
, , "The
time is HH:mm now.", , mm
. ,
"Incorrect time!".
, ,
:
- .
- .
- .
,
, ,
.. . , 0
23 , 0 59 .
( )
112

, ,
.
:
DataValidation.java
import java.util.Scanner;

publicclass DataValidation {

publicstaticvoid main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.println("What time is it?");

System.out.print("Hours: ");
int hours = input.nextInt();

System.out.print("Minutes: ");
int minutes = input.nextInt();

boolean isValidTime =
validateHours(hours) &&validateMinutes(minutes);
if (isValidTime) {
System.out.printf(
"The

time

is

%d:%d

now.%n",

minutes);
} else {
System.out.println("Incorrect time!");

113

hours,

}
}

publicstaticboolean validateHours(int hours) {


boolean result = (hours >= 0) && (hours < 24);
return result;
}

publicstaticboolean validateMinutes(int minutes) {


boolean result = (minutes >= 0) && (minutes <= 59);
return result;
}
}
, , validateHours(),
int, boolean, ..
true false :
publicstaticboolean validateHours(int hours) {
boolean result = (hours >= 0) && (hours < 24);
return result;
}
, ,
. validateMinutes(),
, boolean.
, -,
0 59 , true, false:
publicstaticboolean validateMinutes(int minutes) {

114

boolean result = (minutes >= 0) && (minutes <= 59);


return result;
}
- ,
main(). , ,
"What time is it?". Scanner,
,
, hours minutes:
Scanner input = new Scanner(System.in);
System.out.println("What tidme is it?");
System.out.print("Hours: ");
int hours = input.nextInt();
System.out.print("Minutes: ");
int minutes = input.nextInt();
,
boolean isValidTime, ,
- validateHours() validateMinutes(),
hours minutes.
,
"" &&:
boolean isValidTime =
validateHours(hours) &&validateMinutes(minutes);
, ,
isValidTime, if,

, .
System.out, isValidTime true, "The

115

time is HH:mm now.", HH


hours, mm minutes. else
, "Incorrect
time!".
:
What time is it?
Hours: 17
Minutes: 33
The time is 17:33 now.
:
What time is it?
Hours: 33
Minutes: -2
Incorrect time!


- , .
strong cohesion. ,
-
-.
!
- , . ,
, sortNumbers(), number()
processing() method2().
, -
.

116

-
( ,
), findSmallestElement() sort(int[] arr)
readInputData().
- Java .
camelCase, .. ,
, .
- , ,
.
.
, , .
.
-
(- , ). ,
, , ,
(
). loose
coupling.
- , - " ".
, ,
-
"" .
- , ,
, , .
, ,

, , ,
. ,

117


, .

1. , "Hello,
<name>!" ( "Hello, Peter!"). ,
.
2. getMax() (int) ,
- . ,
- ,
getMax().
3. ,
. : 512 "two";
1024 "four".
4. ,
. ,
.
5. , ,
, -, - .

118

12.
, .

Java.
Java
.

119

You might also like