Java бағдарламалау/Айнымалылар
Java бағдарламалау тілінде өріс және айнымалы сөздер бір және бір нәрсе. Айнымалылар - сандар немесе таңба деректерінің жолы сияқты деректерді сақтау үшін пайдаланылатын құрылғылар.
Java программалауындағы айнымалылар Java қатты терілген бағдарламалау тілі ретінде қарастырылады. Осылайша, Java бағдарламалау тіліндегі барлық айнымалылар белгілі бір деректер түріне ие болуы керек. Бұл жарияланады немесе қорытындыланады және Java тілі бағдарламаларды тек типтік шектеулерді сақтаған жағдайда ғана іске қосуға мүмкіндік береді.
Егер сіз сандық емес деректермен сандық типті ұсынсаңыз, мысалы, мәтіндік мазмұн, онда мұндай мәлімдемелер Java типтік жүйесін бұзады. Бұл Java-ға типті қауіпсіздік мүмкіндігін береді. Java өрнектің немесе деректердің қате түрі бар немесе мүлде кездеспейтінін тексереді. Содан кейін ол бұл оқиғаны компиляция уақытында қате ретінде автоматты түрде белгілейді. Түрге қатысты қателердің көпшілігін Java компиляторы ұстайды, осылайша толық және сәтті құрастырылғаннан кейін бағдарламаны қауіпсіз және қауіпсіз етеді. Кейбір тілдер (мысалы, C) мұндай мәлімдеменің интерпретациясын анықтайды және бұл түсіндіруді ешқандай ескертусіз пайдаланады; басқалары (мысалы, PL/I) осындай барлық дерлік мәлімдемелер үшін түрлендіруді анықтайды және тапсырманы аяқтау үшін түрлендіруді орындайды. Кейбір түр қателері орындалу уақытында әлі де орын алуы мүмкін, себебі Java бір өрнек түрін екіншісіне өзгерту тәсілі болып табылатын трансляциялау әрекетін қолдайды. Дегенмен, Java мұндай трансляцияларды орындау кезінде орындалу уақытының түрін тексеруді орындайды, сондықтан қате түрдегі трансляция дыбыссыз сәтті орындалып, деректердің бүлінуіне жол бермей, орындалу уақытының ерекшелігін тудырады.
Екінші жағынан, Java гибридті тіл ретінде де белгілі. Объектіге бағытталған бағдарламалауды (OOP) қолдағанымен, Java Smalltalk немесе Ruby сияқты таза OO тілі емес. Оның орнына Java нысан түрлерін де, қарапайым типтерді де ұсынады. Қарапайым типтер логикалық, таңбалық және сандық мәндер мен операциялар үшін қолданылады. Бұл икемділік есебінен сандық деректерді өңдеу кезінде салыстырмалы түрде жақсы өнімділікке мүмкіндік береді. Мысалы, қарабайыр типтерді ішкі сыныпқа бөліп, оларға жаңа амалдар қосуға болмайды.
Айнымалылар түрлері Java бағдарламалау тілінде айнымалылардың төрт түрі бар.
Computer code Code listing 3.9: ClassWithVariables.java public class ClassWithVariables {
public int id = 0; public static boolean isClassUsed;
public void processData(String parameter) {
Object currentValue = null;
}
} In the code listing 3.9, are examples of all four kinds of variables.
Дана айнымалылары: Бұл нысанның күйін сақтау үшін пайдаланылатын айнымалылар (мысалы, id). Класс анықтамасынан жасалған әрбір нысанда айнымалының өз көшірмесі болады. Ол сәйкес нысан жадта болғанша жарамды және сақтау орнын алады. Класс айнымалы мәндері: Бұл айнымалы мәндер статикалық модификатормен (мысалы, isClassUsed) класс деңгейіндегі ауқымда анық анықталған. Ешбір басқа айнымалылардың оларға тіркелген статикалық модификаторы болуы мүмкін емес. Бұл айнымалылар статикалық модификатормен анықталғандықтан, сынып қанша рет жасалғанына қарамастан, бұл айнымалылардың бір көшірмесі әрқашан болады. Олар сынып жадқа жүктелгенше өмір сүреді. Параметрлер немесе аргументтер: бұл әдіс қолтаңбасына жіберілген айнымалылар (мысалы, параметр). Негізгі әдісте args айнымалысының қолданылуын еске түсіріңіз. Олар модификаторларға (яғни, жалпыға ортақ, жеке, қорғалған немесе статикалық) қосылмаған және оларды әдістің барлық жерінде пайдалануға болады. Олар әдісті орындау кезінде жадта болады және әдіс қайтарылғаннан кейін оны пайдалану мүмкін емес. Жергілікті айнымалылар: Бұл айнымалы мәндер әдіс қолтаңбасында емес, әдіс деңгейі ауқымында (мысалы, currentValue) арнайы анықталған және пайдаланылады. Оларда оған қосылған модификаторлар жоқ. Әдіс қайтарылғаннан кейін олар енді жоқ. Біліміңді сына Айнымалыларды құру
Компьютер жадысының графикалық көрінісі Айнымалылар және олар сақтайтын барлық ақпарат қол жеткізу үшін компьютер жадында сақталады. Компьютер жадын деректер кестесі ретінде елестетіп көріңіз, мұнда әрбір ұяшық айнымалыға сәйкес келеді.
Айнымалы мәнді жасағаннан кейін біз негізінен жаңа мекенжай кеңістігін жасаймыз және оған бірегей атау береміз. Java бір қадам алға жылжиды және айнымалының ішіне не орналастыруға болатынын анықтауға мүмкіндік береді — Java тілінде оны деректер түрі деп атайсыз. Сонымен, айнымалы мәнді жасау үшін екі нәрсені істеу керек:
Айнымалыға бірегей атау беру арқылы жасаңыз; және, Айнымалы үшін деректер түрін анықтаңыз. Келесі код қарапайым айнымалыны қалай жасауға болатынын көрсетеді. Бұл процесс айнымалы декларация ретінде белгілі.
Example Code section 3.40: A simple variable declaration. int a;
Айнымалыларға мәндерді тағайындау Біз айнымалы үшін деректер түрін бергендіктен, бізде айнымалы нені ұстай алатыны және нені ұстай алмайтыны туралы кеңес бар. Біз int (бүтін) деректер түрі оң немесе теріс бүтін сандарды қолдайтынын білеміз. Сондықтан айнымалы жасалғаннан кейін біз оны келесі синтаксисті пайдаланып кез келген бүтін мәнмен қамтамасыз ете аламыз. Бұл процесс тағайындау операциясы деп аталады.
Example Code section 3.41: Variable declaration and assignment operation (on different lines). int a; a = 10; Java provides programmers with a simpler way of combining both variable declaration and assignment operation in one line. Consider the following code:
Example Code section 3.42: Variable declaration and assignment operation (on the same line). int a = 10; Grouping variable declarations and assignment operations Consider the following code:
Example Code section 3.43: Ungrouped declarations. int a; int b; String c; a = 10; b = 20; c = "some text"; There are various ways by which you can streamline the writing of this code. You can group the declarations of similar data types in one statement, for instance:
Example Code section 3.44: Grouped declarations. int a, b; String c; a = 10; b = 20; c = "some text"; Alternatively, you can further reduce the syntax by doing group declarations and assignments together, as such:
Example Code section 3.45: Grouped declarations and assignments. int a = 10, b = 20; String c = "some text"; Identifiers Although memory spaces have their own addresses — usually a hash number such as 0xCAD3, etc. — it is much easier to remember a variable's location in the memory if we can give it a recognizable name. Identifiers are the names we give to our variables. You can name your variable anything like aVariable, someVariable, age, someonesImportantData, etcetera. But notice: none of the names we described here has a space within it. Hence, it is pretty obvious that spaces aren't allowed in variable names. In fact, there are a lot of other things that are not allowed in variable names. The things that are allowed are:
Characters A to Z and their lower-case counterparts a to z. Numbers 0 to 9. However, numbers should not come at the beginning of a variable's name. And finally, special characters that include only $ (dollar sign) and _ (underscore). Test your knowledge Any valid variable names might be correct but they are not always what you should be naming your variables for a few reasons as listed below:
The name of the variable should reflect the value within them. The identifier should be named following the naming guidelines or conventions for doing so. We will explain that in a bit. The identifier shouldn't be a nonsense name like lname, you should always name it properly: lastName is the best way of naming a variable. Naming conventions for identifiers When naming identifiers, you need to use the following guidelines which ensure that your variables are named accurately. As we discussed earlier, we should always name our variables in a way that tells us what they hold. Consider this example:
Example Code section 3.46: Unknown process. int a = 24; int b = 365; int c = a * b; Do you know what this program does? Well, it multiplies two values. That much you guessed right. But, do you know what those values are? Exactly, you don't. Now consider this code:
Example Code section 3.47: Time conversion. int age = 24; int daysInYear = 365; int ageInDays = age * daysInYear; Now you can tell what's happening, can't you? However, before we continue, notice the case of the variables. If a word contains CAPITAL LETTERS, it is in UPPER CASE. If a word has small letters, it is in lower case. Both cases in a word renders it as mIxEd CaSe.
The variables we studied so far had a mixed case. When there are two or more words making up the names of a variable, you need to use a special case called the camel-case. Just like the humps of a camel, your words need to stand out. Using this technique, the words first and name could be written as either firstName or FirstName.
The first instance, firstName is what we use as the names of variables. Remember though, firstName is not the same as FirstName because Java is case-sensitive. Case-sensitive basically implies that the case in which you wrote one word is the case you have to call that word in when using them later on. Anything other than that is not the same as you intended. You'll know more as you progress. You can hopefully tell now why the variables you were asked to identify weren't proper.
Literals (values) Now that we know how variables should be named, let us look at the values of those variables. Simple values like numbers are called literals. This section shows you what literals are and how to use them. Consider the following code:
Example Code section 3.48: Literals. int age = 24; long bankBalance = 20000005L; By now, we've only seen how numbers work in assignment statements. Let's look at data types other than numbers. Characters are basically letters of the English alphabet. When writing a single character, we use single quotes to encapsulate them. Take a look at the code below:
Example Code section 3.49: Character. char c = 'a'; Why, you ask? Well, the explanation is simple. If written without quotes, the system would think it's a variable identifier. That's the very distinction you have to make when differentiating between variables and their literal values. Character data types are a bit unusual. First, they can only hold a single character. What if you had to store a complete name within them, say John, would you write something like:
Example Code section 3.50: Character list. char firstChar = 'J'; char secondChar = 'o'; char thirdChar = 'h'; char fourthChar = 'n'; Now, that's pathetic. Thankfully, there's a data type that handles large number of characters, it's called a String. A string can be initialized as follows:
Example Code section 3.51: String. String name = "John"; Notice, the use of double quotation marks instead of single quotation marks. That's the only thing you need to worry about.