Мазмұнға өту

Java бағдарламалау/Мәлімдеме

Уикикітап жобасынан

Жүйелерімізде Java платформасы бар және бірінші бағдарламаны сәтті іске қосқаннан кейін біз бағдарламалардың қалай жасалатынын түсінуге тырысамыз. Жоғарыда талқылағанымыздай, бағдарлама компьютерге берілген тапсырмалар болып табылатын нұсқаулар жиынтығы. Бұл нұсқаулар Java тіліндегі мәлімдемелер деп аталады. Мәліметтер кодтың бір жолынан күрделі математикалық теңдеуге дейінгі кез келген нәрсе болуы мүмкін. Келесі жолды қарастырыңыз:

Мысал Код бөлімі 3.1: Қарапайым тапсырма мәлімдемесі.

int age = 24;

Бұл жол жүйеге айнымалыны инициализациялауды және оның мәнін 24 етіп орнатуды айтатын қарапайым нұсқау болып табылады. Егер жоғарыдағы оператор бағдарламада жалғыз болса, ол келесіге ұқсас болады:

Компьютер коды Код листинг 3.1: Қарапайым сыныптағы мәлімдеме.

public class MyProgram
 {
    public static void main(String[] args) 
    {
        int age = 24;
    }
 }

Java өз мәлімдемелерін сынып декларациясының ішінде орналастырады және класс декларациясында мәлімдемелер әдетте жоғарыдағыдай әдіс мәлімдемесінде орналастырылады.

Айнымалылар туралы мәлімдеме

[өңдеу]

Ең қарапайым мәлімдеме айнымалы мәлімдеме болып табылады:

Мысал Код бөлімі 3.2: Қарапайым мәлімдеме мәлімдемесі.

int age;


Ол кейінірек пайдалану үшін мәндерді сақтау үшін пайдаланылатын айнымалыны анықтайды. Бірінші таңбалауыш айнымалының деректер түрі болып табылады (бұл айнымалы мәндердің қай түрін сақтай алады). Екінші таңбалауыш - айнымалының аты, ол арқылы сіз оған сілтеме жасайсыз. Содан кейін әрбір мәлімдеме мәлімдемесі нүктелі үтірмен (;) аяқталады.

Тапсырма туралы мәлімдемелер

[өңдеу]

Осы уақытқа дейін біз айнымалыларды құруды бір мәлімдеме ретінде қабылдадық. Негізінде, біз сол айнымалыларға мән тағайындаймыз және ол дәл осылай аталады. Операциядағы айнымалыға мән тағайындаған кезде, бұл мәлімдеме тағайындау операторы деп аталады (сонымен қатар инициализация операторы деп аталады). Сіз тағы бір нәрсені байқадыңыз ба? Бұл әр мәлімдеменің соңында орналасқан нүктелі үтір (;). Код жолы мәлімдеме болып табылатынының айқын көрсеткіші оның соңындағы нүктелі үтірмен аяқталуы болып табылады. Егер біреу бірнеше мәлімдеме жазу керек болса, ол әдетте нүктелі үтірмен аяқталатын бөлек жолда әрбір оператормен орындалады. Төмендегі мысалды қарастырыңыз:

Мысал код бөлімі 3.3: Бірнеше тағайындау мәлімдемелері.

int a = 10;
int b = 20;
int c = 30;

Әрбір мәлімдемені жазу үшін міндетті түрде жаңа жолды пайдаланудың қажеті жоқ. Ағылшын тілі сияқты, төменде көрсетілгендей біріншісін аяқтаған келесі мәлімдемені жазуды бастай аласыз:

Мысал код бөлімі 3.4: Бір жолда бірнеше тағайындау мәлімдемелері.


int a = 10; 
int b = 20; 
int c = 30;

Дегенмен, бірнеше мәлімдемелерді бір жолға қоюдың жалғыз проблемасы - оны оқу өте қиын. Бастапқыда бұл соншалықты қорқынышты болып көрінбейді, бірақ сізде кодтың айтарлықтай көлемін алғаннан кейін, әдетте оны мағынасы бар етіп ұйымдастырған дұрыс. Ол 3.4-тізімде жазылғандай күрделірек және түсініксіз болып көрінеді.

Енді біз қарапайым тапсырма мәлімдемесінің анатомиясын қарастырғаннан кейін, біз қол жеткізген нәрсеге қайта қарай аламыз. Біз мұны білеміз...

Мәлімдеме – программалаудағы код бірлігі. Егер айнымалыға мән тағайындайтын болсақ, оператор тағайындау операторы деп аталады. Тағайындау мәлімдемесі үш бөліктен тұрады: деректер түрі, айнымалы атауы (идентификатор деп те аталады) және айнымалының мәні. Идентификаторлар мен мәндердің табиғатын кейінірек Айнымалылар бөлімінде қарастырамыз. Енді келесі тақырыпқа өтпес бұрын төмендегі кодтың не істейтінін түсінуге тырысу керек.

Мысал код бөлімі 3.5: өрнектері бар бірнеше тағайындау мәлімдемелері.


int firstNumber = 10;
int secondNumber = 20;
int result = firstNumber + secondNumber;
System.out.println(result);
secondNumber = 30; // This won't change the value of secondNumber. See the note.
System.out.println(result); // Hence, the result will remain same.


Алғашқы екі мәлімдеме 3.3-бөлімдегіге ұқсас, бірақ айнымалы атаулары әртүрлі. Үшіншісі аздап қызықты. Біз сыйлық қораптарына ұқсас айнымалылар туралы бұрын айтқан болатынбыз. Компьютер жадын барлық қораптарды қоятын сөре ретінде қарастырыңыз. Сізге қорап (немесе айнымалы) қажет болғанда, сіз оның идентификаторын шақырасыз (бұл айнымалының аты). Сондықтан firstNumber айнымалы идентификаторын шақыру сізге 10 санын береді, ал secondNumber шақыру сізге 20 береді, сондықтан екеуін қосқанда жауап 30 болуы керек. Соңғы айнымалы нәтиженің мәні осылай болады. Үшінші мәлімдеменің сандарды қосатын бөлігі, яғни біріншіNumber + secondNumber өрнек деп аталады және өрнек мәннің қандай болатынын шешеді. Егер бұл алғашқы екі мәлімдемедегідей жай мән болса, онда ол литерал деп аталады (мән сөзбе-сөз мән, демек литерал атауы).

Нәтижеге тағайындаудан кейін оның мәні өзгермейтінін ескеріңіз, егер 5-жолдағы сияқты бірінші немесе екінші санға әртүрлі мәндер тағайындасақ.

Жаңа ғана алған ақпаратпен сіз мәндерді қорытындылай алатын лайықты Java бағдарламасын жаза аласыз.

Бекіту

[өңдеу]

Бекіту шарттың дұрыстығын тексереді:

Мысал код бөлімі 3.6: Қайтару мәлімдемесі.

public int getAge() 
    {
        assert age >= 0;
        return age;
    }

Әрбір бекіту мәлімдемесі нүктелі үтірмен (;) аяқталады. Дегенмен, бекітулер әдепкі бойынша өшірілген, сондықтан бекітулер қосулы болу үшін бағдарламаны -ea аргументі арқылы іске қосу керек (java -ea [құрастырылған бағдарламаның аты]).

Бағдарламаны басқару ағыны

[өңдеу]

Мәлімдемелер орын алу ретімен бағаланады. Ағынның орындалуы ең жоғарғы оператордан басталып, соңғы оператор кездескенше төмен қарай жалғасады. Мәлімдеме оператор блогымен ауыстырылуы мүмкін. Шарт негізінде орындалу ағынын қайта бағыттай алатын арнайы мәлімдемелер бар, бұл мәлімдемелер кейінірек бөлімде егжей-тегжейлі сипатталған тармақталған операторлар деп аталады.

Мәлімдеме блоктары

[өңдеу]

Бір блок ретінде орындалатын жақшаға бірнеше мәлімдемелерді орналастыруға болады. Мұндай мәлімдемелер блогын атауға немесе орындау шартымен қамтамасыз етуге болады. Төменде блокта мәлімдемелер қатарын қалай орналастыру керектігі көрсетілген.

Мысал код бөлімі 3.7: мәлімдеме блогы.

{
    int a = 10;
    int b = 20;
    int result = a + b;
}

Тармақтық мәлімдемелер

[өңдеу]

Бағдарлама ағынына функция/метод шақырулары, циклдар және итерациялар арқылы әсер етуге болады. Тармақталған конструкциялардың әртүрлі түрлерінің ішінен біз екі жалпы тармақталу әдісін оңай таңдай аламыз.

  • Шартсыз тармақталу
  • Шартты тармақталу

Шартсыз тармақталу мәлімдемелері

[өңдеу]

Егер сіз методке мұқият қарасаңыз, метод белгілі бір атауды шақыру арқылы орындалатын аталған мәлімдеме блогы екенін көресіз. Шартсыз тармақ методті шақыру арқылы немесе break, continue, return немесе throw шақыру арқылы жасалады, олардың барлығы төменде сипатталған.

Ағында басқа әдістің атауы кездескен кезде, ол ағымдағы әдісте орындауды тоқтатады және жаңадан шақырылған методке тармақталады. Шақырылған әдістен мәнді қайтарғаннан кейін орындау әдіс шақыруының астындағы жолдағы бастапқы әдісте қабылданады.

Компьютер коды Кодтар тізімі 3.8: UnconditionalBranching.java

public class UnconditionalBranching {
    public static void main(String[] args) {
        System.out.println("Inside main method! Invoking aMethod!");
        aMethod();
        System.out.println("Back in main method!");
    }

    public static void aMethod() {
        System.out.println("Inside aMethod!");
    }
}


Стандартты кіріс немесе шығыс

Жоғарыдағы кодпен жұмыс істейтін ақпарат экранымен қамтамасыз етілген шығыс. Негізгі әдістің ішінде! aMethod шақыру! Inside aMethod! Негізгі әдіске қайта оралыңыз! Бағдарлама ағыны негізгі әдістен басталады. aMethod шақырылғандай, ағын шақырылған әдіске өтеді. Дәл осы сәтте ағын басқа әдіске тармақталады. Әдіс аяқталғаннан кейін ағын қалдырылған нүктеге қайтарылады және әдіске шақырудан кейінгі келесі мәлімдемеде жалғасады.

Қайтару мәлімдемесі Қайтару операторы блоктан шығады, сондықтан ол көбінесе әдістің соңғы мәлімдемесі болып табылады:

Мысал Код бөлімі 3.9: Қайтару мәлімдемесі.


public int getAge() {
        int age = 24;
        return age;
    }


A return statement can return the content of a variable or nothing. Beware not to write statements after a return statement which would not be executed! Each return statement is ended by a semi-colon (;).

Conditional Branching Statements Conditional branching is attained with the help of the if...else and switch statements. A conditional branch occurs only if a certain condition expression evaluates to true.

Conditional Statements Also referred to as if statements, these allow a program to perform a test and then take action based on the result of that test.

The form of the if statement:

if (condition) {
  do statements here if condition is true
} else {
  do statements here if condition is false
}

The condition is a boolean expression which can be either true or false. The actions performed will depend on the value of the condition.

Example:

Example Code section 3.10: An if statement.

if (i > 0) {
   System.out.println("value stored in i is greater than zero");
} else {
   System.out.println("value stored is not greater than zero");
}

If statements can also be made more complex using the else if combination:


if (condition 1) {
   do statements here if condition 1 is true
} else if (condition 2) {
   do statements here if condition 1 is false and condition 2 is true
} else {
  do statements here if neither condition 1 nor condition 2 is true
}

Example:

Example Code section 3.11: An if/else if/else statement.

if (i > 0) {
   System.out.println("value stored in i is greater than zero");
} else if (i < 0) {
   System.out.println("value stored in i is less than zero");
} else {
   System.out.println("value stored is equal to 0");
}

If there is only one statement to be executed after the condition, as in the above example, it is possible to omit the curly braces, however Oracle's Java Code Conventions explicitly state that the braces should always be used.

There is no looping involved in an if statement so once the condition has been evaluated the program will continue with the next instruction after the statement.

If...else statements The if ... else statement is used to conditionally execute one of two blocks of statements, depending on the result of a boolean condition.

Example:

Example Code section 3.12: An if/else statement.

if (list == null) {
  // This block of statements executes if the condition is true.
} else {
  // This block of statements executes if the condition is false.
}

Oracle's Java Code Conventions recommend that the braces should always be used.

An if statement has two forms:

if (boolean-condition)
   statement1
and

if (boolean-condition)
   statement1
else
   statement2

Use the second form if you have different statements to execute if the boolean-condition is true or if it is false. Use the first if you only wish to execute statement1 if the condition is true and you do not wish to execute alternate statements if the condition is false.

The code section 3.13 calls two int methods, f() and y(), stores the results, then uses an if statement to test if x is less than y and if it is, the statement1 body will swap the values. The end result is x always contains the larger result and y always contains the smaller result.

Example Code section 3.13: Value swap.

int x = f();
int y = y();
if (x < y) {
  int z = x;
  x = y;
  y = z;
}

if...else statements also allow for the use of another statement, else if. This statement is used to provide another if statement to the conditional that can only be executed if the others are not true. For example:

Example Code section 3.14: Multiple branching.

if (x == 2)
  x = 4;
else if (x == 3)
  x = 6;
else
  x = -1;

The else if statement is useful in this case because if one of the conditionals is true, the other must be false. Keep in mind that if one is true, the other will not execute. For example, if the statement at line 2 contained in the first conditional were changed to x = 3;, the second conditional, the else if, would still not execute. However, when dealing with primitive types in conditional statements, it is more desirable to use switch statements rather than multiple else if statements.

Switch statements The switch conditional statement is basically a shorthand version of writing many if...else statements. The syntax for switch statements is as follows:

switch(<variable>) {
  case <result>: <statements>; break;
  case <result>: <statements>; break;
  default: <statements>; break;
}

This means that if the variable included equals one of the case results, the statements following that case, until the word break will run. The default case executes if none of the others are true. Note: the only types that can be analysed through switch statements are char, byte, short, or int primitive types. This means that Object variables can not by analyzed through switch statements. However, as of the JDK 7 release, you can use a String object in the expression of a switch statement.

Example Code section 3.15: A switch.

int n = 2, x;
switch (n) {
  case 1: x = 2;
    break;
  case 2: x = 4;
    break;
  case 3: x = 6;
    break;
  case 4: x = 8;
    break;
}
return x;

In this example, since the integer variable n is equal to 2, case 2 will execute, make x equal to 4. Thus, 4 is returned by the method.

Iteration Statements Iteration Statements are statements that are used to iterate a block of statements. Such statements are often referred to as loops. Java offers four kinds of iterative statements.

The while loop The do...while loop The for loop The foreach loop The while loop Main article: Java Programming/Keywords/while The while loop iterates a block of code while the condition it specifies is true.

The syntax for the loop is:

while (condition) {
   statement;
 }

Here the condition is an expression. An expression as discussed earlier is any statement that returns a value. While condition statements evaluate to a boolean value, that is, either true or false. As long as the condition is true, the loop will iterate the block of code over and over and again. Once the condition evaluates to false, the loop exits to the next statement outside the loop.

The do...while loop The do-while loop is functionally similar to the while loop, except the condition is evaluated AFTER the statement executes

do {
   statement;
 } while (condition);

The for loop Main article: Java Programming/Keywords/for The for loop is a specialized while loop whose syntax is designed for easy iteration through a sequence of numbers. Example:

Example Code section 3.16: A for loop.

for (int i = 0; i < 100; i++) {
  System.out.println(i + "\t" + i * i);
}

Standard input or output Output for code listing 3.16 if you compile and run the statement above.

0      0
1      1
2      4
3      9
...
99     9801

The program prints the numbers 0 to 99 and their squares.

The same statement in a while loop:

Example Code section 3.17: An alternative version.

int i = 0;
while (i < 100) {
   System.out.println(i + "\t" + i * i);
   i++;
}

The foreach loop The foreach statement allows you to iterate through all the items in a collection, examining each item in turn while still preserving its type. The syntax for the foreach statement is:

for (type item : collection) statement; For an example, we'll take an array of Strings denoting days in a week and traverse through the collection, examining one item at a time.

Example Code section 3.18: A foreach loop.

String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

for (String day : days) {
  System.out.println(day);
}


Standard input or output Output for code listing 3.18 Monday Tuesday Wednesday Thursday Friday Saturday Sunday Notice that the loop automatically exits after the last item in the collection has been examined in the statement block.

Although the enhanced for loop can make code much clearer, it can't be used in some common situations.

Only access. Elements can not be assigned to, eg, not to increment each element in a collection. Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays. Only single element. Use only for single element access, eg, not to compare successive elements. Only forward. It's possible to iterate only forward by single steps. At least Java 5. Don't use it if you need compatibility with versions before Java 5. The continue and break statements At times, you would like to re-iterate a loop without executing the remaining statement within the loop. The continue statement causes the loop to re-iterate and start over from the top most statement inside the loop.

Where there is an ability to re-iterate the loop, there is an ability to exit the loop when required. At any given moment, if you'd like to exit a loop and end all further work within the loop, the break ought to be used.

The continue and break statements can be used with a label like follows:

Example Code section 3.19: Using a label. String s = "A test string for the switch!\nLine two of test string..."; outer: for (int i = 0; i < s.length(); i++) {

 switch (s.charAt(i)) {
   case '\n': break outer;
   case ' ': break;
   default: System.out.print(s.charAt(i));
 }

} Standard input or output Output for code listing 3.19

Ateststringfortheswitch!


Throw statement A throw statement exits from a method and so on and so on or it is caught by a try/catch block. It does not return a variable but an exception:

Example Code section 3.20: A return statement.

public int getAge() {
        throw new NullPointerException();
    }


Beware not to write statements after a throw statement which would not be executed too! Each throw statement is ended by a semi-colon (;).

try/catch A try/catch must at least contain the try block and the catch block:

Example Code section 3.21: try/catch block.


try {
  // Some code
} catch (Exception e) {
  // Optional exception handling
} finally {
  // This code is executed no matter what
}