Content
Primitive types
The primitive types are divided into:
- Characters
- char
- String
- boolean
- Numeric
- Integers
- byte
- short
- int
- long
- Real
- float
- double
- Integers
- Arrays
The primitive types are characterized by having defined a same size on all platforms (unlike the C / C++)
The literal real are of type double unless you include the suffix F
3.14 it is not of the same type 3.14 Fthe first will be double and the second float
When you want to cause a conversion uses the operator cast
It has the following syntax:
Using the cast, you can perform those conversions that the compiler does not by default
In the example, has carried out a casting of the double 5.4 a int to store it in the variable i
The result of that operation will be the compiler to take only the integer part of the double, that is to say, will keep on i the value 5
In the second operation example, it is divided 5 by 2, this operation will return its result as a double, but if the result would not have decimal places, would be saved as a whole
To make a casting in the denominator, we force the compiler to store the result of the division as a double even if you have no decimal
Keep in mind, that a casting does not correct the error of division by 0, should be controlled by the use of exceptions
Wrappers
A wapper is a wrap that is applied to a primitive type concrete
There are a class wrapper is associated to each primitive type
In the example, we have redefined the wrappers for int (it is Integer) and for double (it is Double) to be able to add the primitive data int and double in the class Vector
The class Wrapper have a second functionality
Are used to locate all those services of the primitive types that they represent
Some methods of wrappers are important:
Integer | Character |
---|---|
MAX_VALUE | chaValue() |
MIN_VALUE | equals(Object) |
Integer(int) | getType(char) |
Integer(String) | isDigit(char) |
byteValue() | isIdentifierIgnorable(char) |
doubleValue() | isJavaIdentifierPart(char) |
equals(Object) | isJavaIdentifierStart(char) |
floatValue() | isJavaLetterOrDigit(char) |
intValue() | isLetter() |
longValue() | isLetterOrDigit(char) |
parseInt(String) | isLowerCase(char) |
parseInt(String, int) | isUpperCase(char) |
shortValue() | isWhitespace(char) |
toBinaryString(int) | toLowerCase(char) |
toHexString(int) | toString() |
toOctalString(int) | toUpperCase(char) |
toString(int, int) | toString(int, int) |
Characters
A character it is a symbol that follows the ASCII standard which we use to generate the texts of our programs
A string of characters it is an array of characters that allow you to save texts or phrases
char
It is a letter that follows the ASCII standard and is the smallest unit of string
Its size is 8 bit
Its value could be considered a small integer since its range is -128 to 127
Values char are associated with the class Character
Is initialized with single quotation marks
In the example initialized the variable ch as a string and as you can see has been saved to the ASCII symbol that corresponds to the letter to uppercase
String
The character strings are not a primitive type
However Java provides special classes for your treatment
Strings are objects that are manipulated using the classes String and StringBuffer
Is used String when the string will not be modified
Use StringBuffer when you want to manipulate the string
It is recommended to use typically the String (to be constant) to be more efficient
Initialization of a String
The strings are between double quotation marks, and character with single quotation marks
When the compiler encounters a string literal, it will create a String object with the text of the same
In the example, we have initialized two variables that might be equivalent
s1 has been initialized using only the double quotation marks
s2 has initializing the constructor for objects of the String class, passing it as an argument the value with double quotation marks
Both initializations are valid and the contents of the variables s1 and s2 will be in both Hello
The only difference is that to be different objects, their reference in memory will also be different
Basic methods
length
The method length returns the number of characters in a string
In the example, we have asked two strings of characters number of characters
In the first you have used double quotation marks, and in the second the String object s1 of the above example
The two previous expressions would be equivalent, return an integer with the number of characters in the string
charAt
The method charAt returns the character at the specified position
If the argument of charAt is not a number between 0 and length – 1 will cause an exception
In the example you have created a function that given a String str and char are looking for, you search for the character in that string and if found, the return value will be greater than 0
To achieve this they have used the method charAt has passed the value of i that represents the position of a character read up to the time
As returns the character read in that time we have been able to compare it with the character search that we passed as an argument
Search methods
Methods to perform searches in strings return the position of the searched item or -1 if not found:
- indexOf(int ch)
- indexOf(int ch, int start)
- indexOf(String str)
- indexOf(String, int start)
- lastIndexOf(int ch)
- lastIndexOf(int ch, int start)
- lastIndexOf(String str)
- lastIndexOf(String str, int start)
In the example we have used each of the methods and discussed its return value to be able to understand them better
Comparison of strings
To compare strings does not serve the = = operator, because in reality we are comparing objects
The String class has several methods for comparing strings
Two strings will be equal if they have the same length and the same characters Unicode (to and unto are different)
The most common methods are:
- equals
- equalsIgnoreCase
distinguishes between uppercase and lowercase
- compareTo
in addition to allowing us to find out if two strings are the same, it also tells us which one is greater than the two:
- Equal to 0
They were the same
- Greater than 0
The second value was greater
- Less than 0
The second value was less
- Equal to 0
In the example we have used each of the methods and discussed its return value to be able to understand them better
Methods for comparing prefixes and suffixes
- boolean starsWith(String)
- boolean starsWith(String, int start)
- boolean endsWith(String)
In the example we have used each of the methods and discussed its return value to be able to understand them better
Extraction of strings
There are a number of methods that return a new string that is the result of manipulating the original string
The original string is not modified (a new instance of the string is created, that is, another memory position is used)
- String concat(String)
- String replace(char, char)
- String replaceAll(String, String)
- String substring(int start)
- String substring(int start, int end)
- String toLowerCase()
- String toUpperCase()
- String trim()
In the example we have used some of the methods and discussed its return value to be able to understand them better
String conversions
The primitive types can be converted automatically to strings
To convert strings to primitive types, use one of the following functions:
- boolean new Boolean(String).booleanValue()
- int Integer.parseInt(String)
- long Long.parseLong(String)
- float Float.parseFloat(String)
- double Double.parseDouble(String)
Other methods
- char[] toCharArray()
- void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)
- int hashCode()
- String valueOf(boolean)
- String valueOf(int)
- String valueOf(long)
- String valueOf(float)
- String valueOf(double)
- String[] split(String)
As you can see in the example, we'll use split to slice strings using a token, in this case we've used space
This method is quite useful for working with text files in CSV format, since the symbol is usually used; (or other token symbol) to separate the different columns or cells
StringBuffer
Although the String class is the most common it is not appropriate for strings that need to be changed frequently
The example creates four String objects of which only one will be used, admiration1 or admiration2
The class StringBuffer lets you modify the original string without the need to create intermediate objects as done in the example
Initialization of a StringBuffer
Supports the following constructors:
- StringBuffer()
- StringBuffer(int i)
- StringBuffer(String str)
Methods of modification
Supports the following modification methods:
- append(Objetc obj)
- append(String str)
- append(char str[] )
- append(boolean b)
- append(int i)
- append(long l)
- append(float f)
- append(double d)
- append(char ch)
- insert(int offset, Object obj)
- insert(int offset, String str)
- insert(int offset, char str[] )
- insert(int offset, boolean b)
- insert(int offset, int i)
- insert(int offset, long l)
- insert(int offset, float f)
- insert(int offset, double d)
- insert(int offset, char ch)
- setCharAt(int index, char c)
- setLength(int longitud)
In the example we have used some of the methods and discussed its return value to be able to understand them better
Basic methods
length
It is similar to the String
charAt
It is similar to the String
toString
Performs the conversion of the BufferString to String
Operador +
Java allows concatenation of strings using the +
In the example, internally the compiler uses a StringBuffer instead of a String
So this example is completely compatible with the previous
In the example we concatenated the string with another type (integer), the latter is automatically converted to string (the compiler implicitly invokes the toString() method of the StringBuffer class)
boolean
Its size is 1 bit
Its value could be considered a small integer since its range is 0 to 1
Being the value 0 equal to FALSE and 1 equal to TRUE
The boolean values are associated to the class Boolean
Basic methods
booleanValue
Returns the value of the boolean
toString
Converts the boolean type to a string
Numeric
Are all types that allow you to work with numbers and can be distinguished according to whether they are integers or decimals, or as to its accuracy
Integers
They are all types that allow you to work with integers, there are several types depending on their accuracy and the range of numbers that can be handled
byte
Its size is 8 bit
Its value could be considered an unsigned small integer since its range is 0 to 255
The byte values are associated with the class Byte
short
Its size is 16 bits
Its value could be considered an unsigned integer since its range is 0 to 65535
The values short are associated to the class Short
int
Its size is 16 bits
Its value could be considered a signed integer since its range is -32768 to 32767
The int values are associated to the class Integer
long
Its size is 32 bits
Its value could be considered a large integer as its range is -2147483648 to 2147483647
The long values are associated with the class Long
Real
They are all types that allow you to work with decimal numbers, there are several types depending on their accuracy and the range of numbers they can handle
float
Its size is 32 bits
Its value would be a decimal smaller as their range is 3.4 E-38 to 3.4 E+38
The float values are associated with the class Float
double
Its size is 64 bits
Its value could be considered as a decimal great since its range is 1.7 E-308 to 1.7 E+308
The double values are associated to the class Double
Arrays
An array is a grouping of elements of the same type
Arrays in Java are objects
Therefore, a reference will be needed to manipulate them
In the example we can see that like any other object, it is initialized with new
Classic array notation (using an index) is used to access array elements (using an index)
If the maximum value of the index is not specified, the compiler will take it as a dynamic array
We can consider that the rating is equivalent to send a message to the array to view an item or edit it
The range of an array is between 0 and N-1 (N being the size of the array)
If you have access to a position out of range an exception will be thrown
In the example we have initialized the array to then be able to view all its contents by screen
As can be seen, Java allows you to initialize the array in its declaration
The operator length allows you to find out the size of an array
In the example we have initialized an array of references in your statement
As can be seen, both statements are equivalent
Arrays two dimensional
A two dimensional array can have multiple rows, and in each row there does not have to be the same number of elements or columns
In the example we have declared and initialized two dimensional array of doubles array then walk it and display it on the screen
The first row has four elements {1,2,3,4}
The second row has two elements {5,6}
The third row has six elements {7,8,9,10,11,12}
The fourth row has an element {13}
array.length gives us the number of rows which in this case is
matrix [i] .length gives us the number of elements in each row
We show the elements of a row separated by a tab using the print function
Once a row is passed to the next by using println
Example of identity matrix
To show the power of a two dimensional matrix, this example builds a dimension identity matrix 4
A identity matrix is the one whose elements are zero except those of the main diagonal, i= =j, which are some
Using a double for loop we loop through the elements of the array specifying its row i and its column j by population the matrix with 1 or 0 depending on whether i and j match
Using a double for loop we go through the elements of the array by specifying its row i and its column j
We show the elements of a row separated by a tab using the print function
Once a row is passed to the next by using println