arrays
in this course we're going to talk about arrays . in java we use arrays to store a list of items like a list of numbers or a list of people or a list of messages . here we have an integer variable . we convert this to an integer array . so right after int we add square brackets . now we have a compilation error . because we're storing a single number in this array . so to fix this we need to remove one . because arrays are reference types . we need to use the new operator here then we repeat the type one more time . here in square brackets we specify the size or the length of this array . how many items do we want to include in this array. let's say five . also we should change the name of this variable from number to numbers . because we're dealing with a list of items . so always pay attention to the name of your variables . now you can access individual items in this array using index. so we type numbers square brackets to reference the first element or first item we use zero. now we can set this to a value like 1 .similarly we can set the second item to 2. now what if we use an invalid index . let's say 10. this array doesn't have to items. so let's see what happens . numbers of 10 we said this to 3 .when we run this program. we get an exception . exception are java way to report errors . so in this case an exception was raised and our program crashed . we'll talk about exceptions in detail later in the course. so now let's remove the last line and sout tab numbers. let's see what we get . we get this weird string in sort of the items in our array . here 's the reason . by default when we print an array . java returns the string which is calculated based on the address of this object in memory . so if you have another array and we print that we're gonna see something different because each object is gonna be in a different memory space okay. now how can we see the actual items in this array .well we have a class in java arrays . let me show you . arrays so this class is defined in java.util package. let's press ENTER now this is import on the top . beautiful. so we can use the dot operator to access the members of this class. here we have a method called toString . now as you see it this method is implemented multiple times. so in the first implementation this method gets a float array in the second implementation it takes an integer array and so on . so for all primitive types as well as reference type this method is implemented mutiple times. this is what we call method overloading . now we can call this method and pass our integer array and this will return the string representation of this array . so we can cut this from here and pass it to our print method like this . now let's run the program one more time and here's our array . beautiful. so the first two items are initialized . the others are set to 0 by default. because here we're dealing with an integer array if you had a boolean array all items why default get initialized to false . if you have a string array all items get initialized to an empty string. now this syntax for creating and initializing an array is a little bit tedious and it's an older syntax there is a newer way to initialize an array if we know the items ahead of time like in this case . so I'm going to remove these two lines .I'm also gonna remove the new operator here we use curly braces and inside these braces we add all the items in this array . let's say 2.3.4.5&1 now we have 5 items so the length of this array is gonna be 5. we can read that using the lengths . so if we type numbers dot look here we have is filled look at the icon it's an F so this is a field which is like a variable in a class and the type of this field is an integer so this returns the numbers of items in this array . let's get that and printed using our print method. like this .take a look . so we get five . now in java arrays have a fixed size . so once we create them we cannot add or remove additional items to them. they have a fixed length if you want to be able to add or remove additonal items from an array. you should use one of the collection classes that we'll talk about later in the future. for now all I want you to rememer is that arrays have a fixed length. now currently our array is not sorted these numbers are in some kind of random order. we can easily sort this array using the sort method of the arrays class. let show you . so I'm gonna remove this line and call arrays dot sort . once again you can see this method is overloaded because it's implemented with different parameter types . so we call this method and pass our numbers array . now when we run this program. we can see our array is sorted beautiful.
multi-dimensional arrays
so yeah I've learned that we use arrays to store a list of objects. in java we can also create multi-dimensional arrays . for example we can create a two-dimensional array to store a matrix or we can create a three-dimensional array to store data for cube . these are useful in scientific computations . let me show you . so here we have a single dimensional array to convert this to a two-dimensional array .we need to add another pair of square brackets . now we have a compilation error because we need to repeat these brackets on the other side . so let's say we want to create a 2 by 3 matrix . so 2 rows and 3 columns . we add in other brackets here and change these lengths to 2 and 3 . so now we have 2 rows and 3 columns . now to access individual items in this array. we need to supply two indexes . first the index of the row . so we can go to the first row and then the first column and initialize that to 1. now let us print this . so sout once again we use our arrays class dot toString and pass this object. take a look once again we get this weird string. because here we 're dealing with a multi-dimensional array . to solve this problem we need to use another method in this class called deepTostring . use this for printing multi-dimensional arrays . take a look now we have this matrix which has two rows and in each row we have three columns . we can also create a three dimensional array . all we have to do is to add another pair of brackets and sepcify the length of that dimensional . pretty easy . now what about the curly brace syntax let me show you . so let's revert this back to a two dimensional array . we 're gonna get rid of the new operator and use curly braces . now let's say in this matrix . we're gonna have two rows and three columns . so each row is an array itself .because it's a list of items right ? so we add another array here . let's say 1 2 3 then comma . now we add the second row we're gonna have 3 numbers 4 5 &6 . now let's remove this line we don't need it anymore and print this array . so here's the end result .
constants
you have learned a lot about variables learned that when declaring them we need to initialize them and we can always change their value later on throughout the lifetime of our programs. however there are times that we don't want the value of a variable to change . for example . let's declare variable called pi and set it to 3.14 . now here we need to add an F to represent this as a float because by default java compiler sees this number as a decimal okay. now you know that we use pi to calculate the area of a circle . what if before we calculate the area of a circle . I come here and type pi equals 1 .then all our calculations are gonna get messed up. we don't want this to happen . that's why we use constants . so if we type final here . java compiler will treat this as a constant. so once we initialize this we cannot change its value .later on(随后) .you can see here we have a compilation error and it says cannot assign a value to final variable pi . so pi is a final variable or a constant . now by convention we use all capital letters to name constants . so this should be PI. now I tell you a little side story in one of me early courses that I created years age that was C# basics for beginners there I used the same example to teach the concept of constants . but I pronounce this word as P instead of PI . and believe it or not to this day people make fun of me for saying P instead PI but that's how we learned this back in Iran we pronounce it as P and I think Greek people also say P but anyway I just thought to share you .
arithmetic expressions
now you're done with constants next we're gonna talk about arithmetic expressions in java. so in java we have the same arithmetic operators that we have in math . we have addtion subtraction multiplication divison and modulus which is the remainder of a divison . let's look at a few example. so I'm gonna declare an integer called result and here we can type 10 plus 3 now . when we print result . It's gonna be 13 pretty (straightforward there you go) so this is addition we also have subtraction multiplication . division is an interesting one. let's take a look (10/3) so here the result is a whole number beacuse in java the division of two whole numbers is a whole number. if you want to get a float-point number here . you need to convert these numbers to a float or a double . let me show you . so we prefix this number with parentheses and in parenthese we type double . now we are casting or converting this number to a double . similarly we should do that here and now we have a compilation error because on the left side we declared an integer but here the result of this expression is a double . and by the way an expression is a piece of code that produces a value . so what we have here is an expression because it produces a value . so to fix this problem need change this to double . now when we run this program we get this floating point number.(beautiful) so these are the arithmetic operators and these numbers that we have here are called operands . we also have increment and decrement operators . let me show you . so I'm gonna declare a new variable int X . we set it to 1. now if you want to increase the value of x by 1 .we use the increment operator . now let's print this on a terminal . so we get 2. (there you go) .we can apply this operaor as a postfix or as a prefix and we get the same result. take a look . 2. however if we use this on the right side of an assignment operator we get different results . let me show you . so I'm gonna declare another variable Y . we set it to X plus plus . in this case because we have applied the increment operator as a postfix . first the value of X will get copied to Y . so Y would be 1 and then X will be incremented by 1. so if you print x and y . x is gonna be 2 and y is gonna be 1 .take a look . so x is 2 and y is 1 (beautiful) however if you apply this as a prefix . first x will be incremented by 1 . so it will be 2 and then it will be copied to y. so in this case both x and y will be two .take a look . so we get two and tow . now what if you want to increment x by more than one . let's say by 2 . well there are two ways to do this . let's remove y . we don't really need it anymore. we can write x equals x plus 2. so first we add 2 to x. the result will be three and then three will be copied into x . the other way is to use the augmented or compound assignment operator . so we can write x plus equals 2 .what we have on line eight is exactly identical to what we have on line 7 . well as you can see it's shorter . so this is a better way to write the same code . now this is one of the augmented assignment operators 增强赋值运算符 we have the augmented assignment orperators for other arithmetic operators . so we can type x minus equals 2 and this would reduce the value of x by 2 . we also have multiply and divide .so these are the augmented or compound assignment operators .
order of operations
right now . I've got a question for you . here we have declared this variable x . it goes to 10 plus 3 times 2. what do you think is the result of this expression. the results is 16 . let's run this program and find out . so run . there you go . we got 16 . but why . well this is a very basic math concept that unfortunately a lot of people don't know . in math the multiplication and division operators have a higher priority . so they get applied first .
in this example . this expression 3 times 2 is evaluated first . the result is 6 and then 6 is added to 10. that's why we get 16 . now if you want to change the order of these operators . you can always use parentheses . for example if you want this expression(10+3) to be evaluated first . we wrap it in parentheses . so like this now . java compiler will first evaluate this expression . the result will be 13 and then 13 is multiplied by 2 . so we get 26 . take a look. there you go. so be aware of the order of these operatations . parentheses always have the highest priority then we have multiplication and division and finally we have addition and subtraction .
casting
we're going to talk about casting and type conversion. so I'm gonna declare a short variable call x and set it to 1 and then I'm gonna declare an integer called y and set it to x plus 2. in this example we're adding a short to an integer . what do you think the result is gonna be . well . let's take a look . so sout . let's print y .we get 3 .that is what you were expecting . but let me explain what happens under the hood .for this expression to get executed because we're dealing with two different types of values . one is short the other is an integer . one of these values should be converted to the other type . so they are equal . now I got a question for you . how many bytes do we have in a short variable . we have 2 bytes . how many bytes do we have in an integer variable . 4 bytes . so any values that we store in a short variable can also be stored in an integer varaible . right . so when this piece of code is gonna get executed . this is what's gonna happen . first java looks at the value in this variable . it's 1 . right . it's going to allocate another variable an anonymous variable somewhere in memory . we don't know where that is .we don't know the name of that variable . it doesn't have a name . it's anonymous , that variable is gonna be an integer then java is gonna copy the value of x into that memory space and then it will add these two numbers together. this is what we call implicit casting . let me type it here . implicit casting that means automatically casting or automatically conversion . we don't have to worry about it .when ever we have a value and that value can be converted to a data type that is bigger casting or conversion happens implicitly or automatically . so byte can be automatically converted to short and this can be converted to int and long . byte > short > int > long > float > double now what about floating-point numbers . let's look at an example . I'm gonna change this to a double one point one . now here we have a compilation error because on the right side of the assignment operator we have a floating-point number . a double on the left side . we have an integer . so we need to change this to double . now when we execute this code . we're gonna get 3.1 . let's vertify this . there you go . now let's see how casting happens here . in this case we're dealing with a double and an integer . an integer is less precise than a double because in a double we can have digits after the decimal point . so in this example java is going to automatically cast this integer to a double . so that will be two point zero . and then 2.0 will be added to 1.1 . so back to this chain here we're gonna have float and then double .so as a general rule of thumb . implicit casting happens whenever you're not gonna lose data . there is no chance for data loss . now what if you want y to be an integer . so in this example we don't care about the digits after the decimal point . you want to see three on the terminal . how should we do this . this is where we should explicitly cast the result . so we should cast x to an integer . like this . parentheses int . this is explicit casting we convert x to an integer . so the result would be one without a decimal point . one will be added to 2 and y would be 3 . take a look . so this is all about implicit and explicit casting . now this explicit casting can only happen between compatible types . so all these types are compatible because they're all numbers . but we cannot cast a string to a number . in other words if x was a string like this let's say 1. we cannot cast x to an integer . because they are not compatible . so how do we do this . for all these primitive types you have learned . you have wrapper classes . so in java we have a class which is a reference type called Integer . this class is defined in java.lang package and in this class we have a method called parseInt() . so this method takes a string and returns an integer. so integer is the wrapper class for the int primitive type. we also have short and in this class we have Short.parseShort (). so it takes a string and returns a short . similarly we have float and double and obviously the name of these metas are different . so here we have parse float . so back to this example let's say we get x as a string and we want to convert it to a integer . this is how we do it . integer.parseInt(x)then add it 2. take a look . we get 3. you might be curious why this matters . why should we parse or convert a string to a number . to add it to something else . well pretty much in most frameworks for building user interfaces whether you're building a desktop or a mobile application or web application . we always receive input from the user as a string . so if you have a form with a bunch of text boxes or drop-down lists . almost always we get values as a string . so that's why we need to convert these strings to their numeric representation . now what if x is a floating-point number here what will happen . when we try to parse this as an integer . let's take a look once again .we get an exception which is how java reports errors to our programs .we're going to talk it in the future. so if the user enters 1.1 . we cannot use this method. instead we should use float or double . let's say double . because that's easier . Double.parse(x) so we parse this number as a double add 2 to it . and then store the result in a double and then we will get 3.1 .
网友评论