Java Tutorial Excelente Importante
-
Upload
pedro-elias-romero-nieto -
Category
Documents
-
view
223 -
download
0
Transcript of Java Tutorial Excelente Importante
-
7/27/2019 Java Tutorial Excelente Importante
1/211
Ejemplo de Interface en Java
1. /*2. Java Interface example.3. This Java Interface example describes how interface is defined and4. being used in Java language.5.6. Syntax of defining java interface is,7. interface {8. //members and methods()9. }10. */11.12. //declare an interface13. interface IntExample{14.15. /*16. Syntax to declare method in java interface is,17. methodName();18. IMPORTANT : Methods declared in the interface are implicitly
public and abstract.19. */20.21. public void sayHello();22. }23. }24. /*25. Classes are extended while interfaces are implemented.26. To implement an interface use implements keyword.27. IMPORTANT : A class can extend only one other class, while it28. can implement n number of interfaces.29. */30.31. public class JavaInterfaceExample implements IntExample{32. /*33. We have to define the method declared in implemented interface,34. or else we have to declare the implementing class as abstract
class.35. */36.37. public void sayHello(){38. System.out.println("Hello Visitor !");39. }40.41. public static void main(String args[]){42. //create object of the class43. JavaInterfaceExample javaInterfaceExample = new
JavaInterfaceExample();44. //invoke sayHello(), declared in IntExample interface.45. javaInterfaceExample.sayHello();46. }47. }48.49. /*50. OUTPUT of the above given Java Interface example would be :51. Hello Visitor !
-
7/27/2019 Java Tutorial Excelente Importante
2/211
52. /*53. Calculate Circle Area using Java Example54. This Calculate Circle Area using Java Example shows how to
calculate55. area of circle using it's radius.56. */57.58. import java.io.BufferedReader;59. import java.io.IOException;60. import java.io.InputStreamReader;61.62. public class CalculateCircleAreaExample {63.64. public static void main(String[] args) {65.66. int radius = 0;67. System.out.println("Please enter radius of a
circle");68.69. try70. {71. //get the radius from console72. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));73. radius = Integer.parseInt(br.readLine());74. }75. //if invalid value was entered76. catch(NumberFormatException ne)77. {78. System.out.println("Invalid radius value" +
ne);79. System.exit(0);80. }81. catch(IOException ioe)82. {83. System.out.println("IO Error :" + ioe);84. System.exit(0);85. }86.87. /*88. * Area of a circle is89. * pi * r * r90. * where r is a radius of a circle.91. */92.93. //NOTE : use Math.PI constant to get value of pi94. double area = Math.PI * radius * radius;95.96. System.out.println("Area of a circle is " + area);97. }98. }99.100./*101.Output of Calculate Circle Area using Java Example would be102.Please enter radius of a circle103.19104.Area of a circle is 1134.1149479459152
-
7/27/2019 Java Tutorial Excelente Importante
3/211
105./*106. Calculate Circle Perimeter using Java Example107. This Calculate Circle Perimeter using Java Example shows
how to calculate108. Perimeter of circle using it's radius.109.*/110.111.import java.io.BufferedReader;112.import java.io.IOException;113.import java.io.InputStreamReader;114.115.public class CalculateCirclePerimeterExample {116.117. public static void main(String[] args) {118.119. int radius = 0;120. System.out.println("Please enter radius of a
circle");121.122. try123. {124. //get the radius from console125. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));126. radius = Integer.parseInt(br.readLine());127. }128. //if invalid value was entered129. catch(NumberFormatException ne)130. {131. System.out.println("Invalid radius value" +
ne);132. System.exit(0);133. }134. catch(IOException ioe)135. {136. System.out.println("IO Error :" + ioe);137. System.exit(0);138. }139.140. /*141. * Perimeter of a circle is142. * 2 * pi * r143. * where r is a radius of a circle.144. */145.146. //NOTE : use Math.PI constant to get value of pi147. double perimeter = 2 * Math.PI * radius;148.149. System.out.println("Perimeter of a circle is " +
perimeter);150. }151.}152.153./*154.Output of Calculate Circle Perimeter using Java Example would be155.Please enter radius of a circle156.19
-
7/27/2019 Java Tutorial Excelente Importante
4/211
157.Perimeter of a circle is 119.38052083641213158.*/159./*160. Calculate Rectangle Area using Java Example161. This Calculate Rectangle Area using Java Example shows how
to calculate162. area of Rectangle using it's length and width.163.*/164.165.import java.io.BufferedReader;166.import java.io.IOException;167.import java.io.InputStreamReader;168.169.public class CalculateRectArea {170.171. public static void main(String[] args) {172.173. int width = 0;174. int length = 0;175.176. try177. {178. //read the length from console179. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));180.181. System.out.println("Please enter length of
a rectangle");182. length = Integer.parseInt(br.readLine());183.184. //read the width from console185. System.out.println("Please enter width of a
rectangle");186. width = Integer.parseInt(br.readLine());187.188.189. }190. //if invalid value was entered191. catch(NumberFormatException ne)192. {193. System.out.println("Invalid value" + ne);194. System.exit(0);195. }196. catch(IOException ioe)197. {198. System.out.println("IO Error :" + ioe);199. System.exit(0);200. }201.202. /*203. * Area of a rectangle is204. * length * width205. */206.207. int area = length * width;208.
-
7/27/2019 Java Tutorial Excelente Importante
5/211
209. System.out.println("Area of a rectangle is " +area);
210. }211.212.}213.214./*215.Output of Calculate Rectangle Area using Java Example would be216.Please enter length of a rectangle217.10218.Please enter width of a rectangle219.15220.Area of a rectangle is 150221.*/222./*223. Find Largest and Smallest Number in an Array Example224. This Java Example shows how to find largest and smallest number
in an225. array.226.*/227.public class FindLargestSmallestNumber {228.229. public static void main(String[] args) {230.231. //array of 10 numbers232. int numbers[] = new
int[]{32,43,53,54,32,65,63,98,43,23};233.234. //assign first element of an array to largest and
smallest235. int smallest = numbers[0];236. int largetst = numbers[0];237.238. for(int i=1; i< numbers.length; i++)239. {240. if(numbers[i] > largetst)241. largetst = numbers[i];242. else if (numbers[i] < smallest)243. smallest = numbers[i];244.245. }246.247. System.out.println("Largest Number is : " +
largetst);248. System.out.println("Smallest Number is : " +
smallest);249. }250.}251.252./*253.Output of this program would be254.Largest Number is : 98255.Smallest Number is : 23256.*/
-
7/27/2019 Java Tutorial Excelente Importante
6/211
1. /*2. Java Factorial Example3. This Java Factorial Example shows how to calculate factorial of4. a given number using Java.5. */6.7. public class NumberFactorial {8.9. public static void main(String[] args) {10.11. int number = 5;12.13. /*14. * Factorial of any number is !n.15. * For example, factorial of 4 is 4*3*2*1.16. */17.18. int factorial = number;19.20. for(int i =(number - 1); i > 1; i--)21. {22. factorial = factorial * i;23. }24.25. System.out.println("Factorial of a number is " +
factorial);26. }27. }28.29. /*30. Output of the Factorial program would be31. Factorial of a number is 12032. */33. /*34. Swap Numbers Java Example35. This Swap Numbers Java Example shows how to36. swap value of two numbers using java.37. */38.39. public class SwapElementsExample {40.41. public static void main(String[] args) {42.43. int num1 = 10;44. int num2 = 20;45.46. System.out.println("Before Swapping");47. System.out.println("Value of num1 is :" + num1);48. System.out.println("Value of num2 is :" +num2);49.50. //swap the value51. swap(num1, num2);52. }53.54. private static void swap(int num1, int num2) {55.56. int temp = num1;
-
7/27/2019 Java Tutorial Excelente Importante
7/211
57. num1 = num2;58. num2 = temp;59.60. System.out.println("After Swapping");61. System.out.println("Value of num1 is :" + num1);62. System.out.println("Value of num2 is :" +num2);63.64. }65. }66.67. /*68. Output of Swap Numbers example would be69. Before Swapping70. Value of num1 is :1071. Value of num2 is :2072. After Swapping73. Value of num1 is :2074. Value of num2 is :1075. */76. /*77. Swap Numbers Without Using Third Variable Java Example78. This Swap Numbers Java Example shows how to79. swap value of two numbers without using third variable
using java.80. */81.82. public class SwapElementsWithoutThirdVariableExample {83.84. public static void main(String[] args) {85.86. int num1 = 10;87. int num2 = 20;88.89. System.out.println("Before Swapping");90. System.out.println("Value of num1 is :" + num1);91. System.out.println("Value of num2 is :" +num2);92.93. //add both the numbers and assign it to first94. num1 = num1 + num2;95. num2 = num1 - num2;96. num1 = num1 - num2;97.98. System.out.println("Before Swapping");99. System.out.println("Value of num1 is :" + num1);100. System.out.println("Value of num2 is :" +num2);101. }102.103.104.}105.106./*107.Output of Swap Numbers Without Using Third Variable example would
be108.Before Swapping109.Value of num1 is :10110.Value of num2 is :20111.Before Swapping
-
7/27/2019 Java Tutorial Excelente Importante
8/211
112.Value of num1 is :20113.Value of num2 is :10114.*/
Interfaz (Java)
interfaz enLenguaje de programacin de Javaestipo abstractocul se utiliza paraespecificarinterfaz(en el sentido genrico del trmino) esoclasesdebe poner en ejecucin.
Los interfaces son el usar declarado interfazpalabra clave, y puede contener solamentemtodofirmas y declaraciones constantes (declaraciones variables se declaran ser que
esttico y final). Un interfaz puede nunca contener definiciones del mtodo.
Como los interfaces estn implcito extracto, no pueden estar directamente instantiated. Lasreferencias del objeto en Java se pueden especificar para estar de un tipo del interfaz; eneste caso deben cualquiera serfalta de informacin, o est limitado a un objeto queinstrumentos el interfaz.
La palabra clave instrumentos se utiliza declarar que una clase dada pone un interfaz enejecucin. Una clase que pone un interfaz en ejecucin debe poner todos los mtodos enejecucin en el interfaz, o seaclase abstracta.
Una ventaja de usar interfaces es que simulanherencia mltiple. Todas las clases en Java
(con excepcin dejava.lang. Objeto,clase de la razde la Javamecanografe elsistema) debe tener exactamente unoclase baja;herencia mltiplede clases no se permite.Sin embargo, una clase de Java/un interfaz puede poner en ejecucin/ampla cualquiernmero de interfaces.
Contenido
1 Interfaces 2 Uso
o 2.1 Definir un interfazo 2.2 Poner un interfaz en ejecucino 2.3 Subinterfaces
3 Ejemplos 4 Modificantes del interfaz de Java 5 Referencias 6 Acoplamientos externos
Interfaces
Los interfaces se utilizan para codificar las semejanzas que las clases de los varios tiposparte, pero necesariamente no constituyen una relacin de la clase. Por ejemplo, ahumano
y aloropoder ambassilbe, no obstante no tendra sentido de representarHumanos y Loros
http://www.worldlingo.com/ma/enwiki/es/Java_%28programming_language%29http://www.worldlingo.com/ma/enwiki/es/Java_%28programming_language%29http://www.worldlingo.com/ma/enwiki/es/Java_%28programming_language%29http://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Interface_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Interface_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Java_keywordshttp://www.worldlingo.com/ma/enwiki/es/Java_keywordshttp://www.worldlingo.com/ma/enwiki/es/Java_keywordshttp://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Pointer_%28computing%29http://www.worldlingo.com/ma/enwiki/es/Pointer_%28computing%29http://www.worldlingo.com/ma/enwiki/es/Pointer_%28computing%29http://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://java.sun.com/javase/6/docs/api/java/lang/Object.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Object.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Object.htmlhttp://www.worldlingo.com/ma/enwiki/es/Top_typehttp://www.worldlingo.com/ma/enwiki/es/Top_typehttp://www.worldlingo.com/ma/enwiki/es/Top_typehttp://www.worldlingo.com/ma/enwiki/es/Type_systemhttp://www.worldlingo.com/ma/enwiki/es/Type_systemhttp://www.worldlingo.com/ma/enwiki/es/Type_systemhttp://www.worldlingo.com/ma/enwiki/es/Type_systemhttp://www.worldlingo.com/ma/enwiki/es/Superclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Superclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Superclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Interfaceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Interfaceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Usagehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Usagehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Defining_an_Interfacehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Defining_an_Interfacehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Implementing_an_Interfacehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Implementing_an_Interfacehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Subinterfaceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Subinterfaceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Exampleshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Exampleshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Java_Interface_modifiershttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Java_Interface_modifiershttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Referenceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Referenceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#External_linkshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#External_linkshttp://www.worldlingo.com/ma/enwiki/es/Humanhttp://www.worldlingo.com/ma/enwiki/es/Humanhttp://www.worldlingo.com/ma/enwiki/es/Humanhttp://www.worldlingo.com/ma/enwiki/es/Parrothttp://www.worldlingo.com/ma/enwiki/es/Parrothttp://www.worldlingo.com/ma/enwiki/es/Parrothttp://www.worldlingo.com/ma/enwiki/es/Whistlehttp://www.worldlingo.com/ma/enwiki/es/Whistlehttp://www.worldlingo.com/ma/enwiki/es/Whistlehttp://www.worldlingo.com/ma/enwiki/es/Whistlehttp://www.worldlingo.com/ma/enwiki/es/Parrothttp://www.worldlingo.com/ma/enwiki/es/Humanhttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#External_linkshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Referenceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Java_Interface_modifiershttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Exampleshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Subinterfaceshttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Implementing_an_Interfacehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Defining_an_Interfacehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Usagehttp://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#Interfaceshttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Superclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Type_systemhttp://www.worldlingo.com/ma/enwiki/es/Type_systemhttp://www.worldlingo.com/ma/enwiki/es/Top_typehttp://java.sun.com/javase/6/docs/api/java/lang/Object.htmlhttp://www.worldlingo.com/ma/enwiki/es/Multiple_inheritancehttp://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Pointer_%28computing%29http://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Java_keywordshttp://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Interface_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Abstract_typehttp://www.worldlingo.com/ma/enwiki/es/Java_%28programming_language%29 -
7/27/2019 Java Tutorial Excelente Importante
9/211
como subclases de a Whistler clasifique, ellos sera algo muy probablemente subclases del
Animal clasifique (probablemente con las clases intermedias), pero ambo instrumento
Whistler interfaz.
Otro uso de interfaces est pudiendo utilizarobjetosin saber su tipo de clase, pero algo
solamente de sa pone cierto interfaz en ejecucin. Por ejemplo, si uno fue molestado porun ruido que silbaba, uno puede no saber si es un ser humano o un loro, todo el que podraser determinado es que un whistler est silbando. En un ejemplo ms prctico, aalgoritmo
que clasificapuede contar con un objeto del tipoComparable. As, sabe que el tipo delobjeto puede ser clasificado de alguna manera, pero es inaplicable cules el tipo del objeto
es. La llamada whistler.whistle () llamar el mtodo puesto en ejecucin silbe del
objeto whistler no importa qu la clase l tiene, con tal que ponga en ejecucin Whistler.
Uso
Definir un interfaz
Los interfaces se deben definir usando el frmula siguiente (compare aDefinicin de laclase de Java).
[visibilidad] interfaz InterfaceName [extiende otros interfaces] {declaraciones constantestipo declaraciones del miembrodeclaraciones abstractos del mtodo}
El cuerpo del interfaz contiene extractomtodos, pero puesto que todos los mtodos en un
interfaz son, por la definicin, extracto, extracto la palabra clave no se requiere. Puestoque el interfaz especifica un sistema de comportamientos expuestos, todos los mtodos
estn implcito pblico.
As, un interfaz simple puede ser
pblico interfaz Despredador {boleano chasePrey(Presa p);vaco eatPrey(Presa p);}
El tipo declaraciones del miembro en un interfaz es implcito esttico y pblico, pero de
otra manera pueden ser cualquier tipo de clase o de interfaz.[1]
Poner un interfaz en ejecucin
El sintaxis para poner un interfaz en ejecucin utiliza este frmula:
... instrumentos InterfaceName[, otro interfaz, otros,]
http://www.worldlingo.com/ma/enwiki/es/Object_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Object_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Object_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Sorting_algorithmhttp://www.worldlingo.com/ma/enwiki/es/Sorting_algorithmhttp://www.worldlingo.com/ma/enwiki/es/Sorting_algorithmhttp://www.worldlingo.com/ma/enwiki/es/Sorting_algorithmhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29#Javahttp://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29#Javahttp://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29#Javahttp://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29#Javahttp://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-0http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-0http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-0http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-0http://www.worldlingo.com/ma/enwiki/es/Method_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29#Javahttp://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29#Javahttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://www.worldlingo.com/ma/enwiki/es/Sorting_algorithmhttp://www.worldlingo.com/ma/enwiki/es/Sorting_algorithmhttp://www.worldlingo.com/ma/enwiki/es/Object_%28computer_science%29 -
7/27/2019 Java Tutorial Excelente Importante
10/211
Clasespuede poner un interfaz en ejecucin. Por ejemplo,
pblico clase Gato instrumentos Despredador {
pblico boleano chasePrey(Presa p) {// que programa para perseguir la presa p (especficamente para un gato)
}
pblico vaco eatPrey (Presa p) {// que programa para comer la presa p (especficamente para un gato)}}
Si una clase pone un interfaz en ejecucin y no esextracto, y no pone todos sus mtodos en
ejecucin, l debe ser marcado como extracto. Si una clase es abstracta, una de susubclasesespera poner sus mtodos en ejecucin unimplemented.
Las clases pueden poner interfaces en ejecucin mltiples
pblico clase Rana instrumentos Depredador, presa { ... }
Los interfaces son de uso general en la lengua de Java paraservicios repetidos.[2]Java nopermite pasar de los mtodos (procedimientos) como discusiones. Por lo tanto, la prcticaes definir un interfaz y utilizarlo como la discusin y utilizar la firma del mtodo que sabeque la firma ser puesta en ejecucin ms adelante.
Subinterfaces
Los interfaces pueden extender varios otros interfaces, usando el mismo frmula se
describen arriba. Por ejemplo
pblico interfaz VenomousPredator extiende Depredador, venenoso {cuerpo de //interface}
es legal y define un subinterface. Nota cmo permite herencia mltiple, desemejante de
clases. Observe tambin eso Despredador y Venenoso puede definir o heredar
posiblemente los mtodos con la misma firma, opinin matanza (presa de la presa).
Cuando instrumentos de una clase VenomousPredator pondr ambos mtodos en ejecucinsimultneamente.
Ejemplos
/** En pocas antiguas, all* eran los monstruos y los Griegos* que se lucharon*/
http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Subclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Subclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Callback_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Callback_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-1http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-1http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-1http://www.worldlingo.com/ma/enwiki/es/Interface_%28Java%29#cite_note-1http://www.worldlingo.com/ma/enwiki/es/Callback_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Subclass_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29http://www.worldlingo.com/ma/enwiki/es/Class_%28computer_science%29 -
7/27/2019 Java Tutorial Excelente Importante
11/211
pblico extracto clase Criatura{protegido Secuencia nombre;//...
pblico vaco ataque(){Sistema.hacia fuera.println(nombre + ataques!);}}
pblico clase Achilles extiende Criatura{//...}
pblico clase Mino extiende Criatura instrumentos Monstruo{//...
pblico vaco rugido(){Sistema.hacia fuera.println(nombre + ruge en alta voz!);}}
pblico interfaz Monstruo{vaco rugido();}
pblico esttico vaco principal(Secuencia[] args){aCreature de la criatura;
//...
/el *** usted tiene que echar aCreature para mecanografiar a monstruo porque* aCreature es un caso de la criatura, y no todo* las criaturas pueden rugir. Sabemos que es un monstruo,* por lo tanto puede rugir porque llegamos si* declaracin abajo. Ambas criaturas pueden atacar, as que nosotros* ataque cueste lo que cueste apenas si es un monstruo que
* como a rugir antes de atacar.*/
si(aCreature instanceof Monstruo){M= del monstruo(Monstruo)aCreature;m.rugido(); monstruo as que nosotros de s. A. de //It el ' podemos rugir}
//Both puede atacaraCreature.ataque();}
-
7/27/2019 Java Tutorial Excelente Importante
12/211
Algunos comunesJavalos interfaces son:
Comparabletiene el mtodocompareTo, que se utiliza para describir dos objetoscomo igual, o indicar uno es el otro mayor que.Genericspermita el poner de clasesen ejecucin para especificar qu casos de la clase se pueden comparar a ellas.
Serializablees ainterfaz del marcadorsin mtodos o campos - tiene un cuerpovaco. Se utiliza para indicar que una clase puede serserializado. SuJavadocdescribe cmo debe funcionar, aunque no se hace cumplir nada programmatically.
Modificantes del interfaz de Java
Tenga acceso al modificante Modificante del interfaz
pblico extracto
privado strictfp
protegido
Debe ser observado que el uso incorrecto de modificantes de interfaces puede dar lugar acomportamiento inestable del software.
http://www.worldlingo.com/ma/enwiki/es/Java_%28software_platform%29http://www.worldlingo.com/ma/enwiki/es/Java_%28software_platform%29http://www.worldlingo.com/ma/enwiki/es/Java_%28software_platform%29http://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.html#compareTo%28T%29http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html#compareTo%28T%29http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html#compareTo%28T%29http://www.worldlingo.com/ma/enwiki/es/Generic_programminghttp://www.worldlingo.com/ma/enwiki/es/Generic_programminghttp://www.worldlingo.com/ma/enwiki/es/Generic_programminghttp://java.sun.com/javase/6/docs/api/java/io/Serializable.htmlhttp://java.sun.com/javase/6/docs/api/java/io/Serializable.htmlhttp://www.worldlingo.com/ma/enwiki/es/Marker_interface_patternhttp://www.worldlingo.com/ma/enwiki/es/Marker_interface_patternhttp://www.worldlingo.com/ma/enwiki/es/Marker_interface_patternhttp://www.worldlingo.com/ma/enwiki/es/Serializationhttp://www.worldlingo.com/ma/enwiki/es/Serializationhttp://www.worldlingo.com/ma/enwiki/es/Serializationhttp://www.worldlingo.com/ma/enwiki/es/Javadochttp://www.worldlingo.com/ma/enwiki/es/Javadochttp://www.worldlingo.com/ma/enwiki/es/Javadochttp://www.worldlingo.com/ma/enwiki/es/Javadochttp://www.worldlingo.com/ma/enwiki/es/Serializationhttp://www.worldlingo.com/ma/enwiki/es/Marker_interface_patternhttp://java.sun.com/javase/6/docs/api/java/io/Serializable.htmlhttp://www.worldlingo.com/ma/enwiki/es/Generic_programminghttp://java.sun.com/javase/6/docs/api/java/lang/Comparable.html#compareTo%28T%29http://java.sun.com/javase/6/docs/api/java/lang/Comparable.htmlhttp://www.worldlingo.com/ma/enwiki/es/Java_%28software_platform%29 -
7/27/2019 Java Tutorial Excelente Importante
13/211
import java.util.*;
public class AClass {
public int instanceInteger = 0;public int instanceMethod() {
return instanceInteger;}
public static int classInteger = 0;public static int classMethod() {
return classInteger;}
public static void main(String[] args) {AClass anInstance = new AClass();AClass anotherInstance = new AClass();
//Refer to instance members through an instance.
anInstance.instanceInteger = 1;anotherInstance.instanceInteger = 2;System.out.format("%s%n", anInstance.instanceMethod());System.out.format("%s%n", anotherInstance.instanceMethod());
//Illegal to refer directly to instance members from a classmethod
//System.out.format("%s%n", instanceMethod()); //illegal//System.out.format("%s%n", instanceInteger); //illegal
//Refer to class members through the class...AClass.classInteger = 7;System.out.format("%s%n", classMethod());
//...or through an instance.System.out.format("%s%n", anInstance.classMethod());
//Instances share class variablesanInstance.classInteger = 9;System.out.format("%s%n", anInstance.classMethod());System.out.format("%s%n", anotherInstance.classMethod());
}}
-
7/27/2019 Java Tutorial Excelente Importante
14/211
package one;
public class Alpha {
//member variablesprivate int privateVariable = 1;
int packageVariable = 2; //default access
protected int protectedVariable = 3;public int publicVariable = 4;
//methodsprivate void privateMethod() {
System.out.format("privateMethod called%n");}void packageMethod() { //default access
System.out.format("packageMethod called%n");}protected void protectedMethod() {
System.out.format("protectedMethod called%n");}
public void publicMethod() {System.out.format("publicMethod called%n");
}
public static void main(String[] args) {Alpha a = new Alpha();a.privateMethod(); //legala.packageMethod(); //legala.protectedMethod(); //legala.publicMethod(); //legal
System.out.format("privateVariable: %2d%n",a.privateVariable); //legal
System.out.format("packageVariable: %2d%n",
a.packageVariable); //legalSystem.out.format("protectedVariable: %2d%n",
a.protectedVariable); //legalSystem.out.format("publicVariable: %2d%n",
a.publicVariable); //legal}
}
-
7/27/2019 Java Tutorial Excelente Importante
15/211
package two;import one.*;
public class AlphaTwo extends Alpha {public static void main(String[] args) {
Alpha a = new Alpha();//a.privateMethod(); //illegal
//a.packageMethod(); //illegal//a.protectedMethod(); //illegala.publicMethod(); //legal
//System.out.format("privateVariable: %2d%n",// a.privateVariable); //illegal//System.out.format("packageVariable: %2d%n",// a.packageVariable); //illegal//System.out.format("protectedVariable: %2d%n",// a.protectedVariable); //illegalSystem.out.format("publicVariable: %2d%n",
a.publicVariable); //legal
AlphaTwo a2 = new AlphaTwo();a2.protectedMethod(); //legalSystem.out.format("protectedVariable: %2d%n",
a2.protectedVariable); //legal}
}
public enum Planet {MERCURY (3.303e+23, 2.4397e6),VENUS (4.869e+24, 6.0518e6),EARTH (5.976e+24, 6.37814e6),MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),SATURN (5.688e+26, 6.0268e7),URANUS (8.686e+25, 2.5559e7),NEPTUNE (1.024e+26, 2.4746e7);
private final double mass; // in kilogramsprivate final double radius; // in metersPlanet(double mass, double radius) {
this.mass = mass;this.radius = radius;
}private double mass() { return mass; }private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)public static final double G = 6.67300E-11;
double surfaceGravity() {return G * mass / (radius * radius);
}double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();}public static void main(String[] args) {
-
7/27/2019 Java Tutorial Excelente Importante
16/211
if (args.length != 1) {System.err.println("Usage: java Planet ");System.exit(-1);
}double earthWeight = Double.parseDouble(args[0]);double mass = earthWeight/EARTH.surfaceGravity();for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",p, p.surfaceWeight(mass));
}}
import java.util.*;
public class Subclass extends Superclass {public boolean aVariable; //hides aVariable in Superclasspublic void aMethod() { //overrides aMethod in Superclass
aVariable = false;super.aMethod();
System.out.format("%b%n", aVariable);System.out.format("%b%n", super.aVariable);
}}
public class Superclass {public boolean aVariable;
public void aMethod() {aVariable = true;
}}
-
7/27/2019 Java Tutorial Excelente Importante
17/211
Abstract Class in java
Java Abstract classes are used to declare common characteristics of subclasses. Anabstract class cannot be instantiated. It can only be used as a superclass for other classesthat extend the abstract class. Abstract classes are declared with the abstract keyword.
Abstract classes are used to provide a template or design for concrete subclasses down theinheritance tree.
Like any other class, an abstract class can contain fields that describe the characteristics andmethods that describe the actions that a class can perform. An abstract class can includemethods that contain no implementation. These are called abstract methods. The abstractmethod declaration must then end with a semicolon rather than a block. If a class has anyabstract methods, whether declared or inherited, the entire class must be declared abstract.Abstract methods are used to provide a template for the classes that inherit the abstractmethods.
Abstract classes cannot be instantiated; they must be subclassed, and actualimplementations must be provided for the abstract methods. Any implementation specifiedcan, of course, be overridden by additional subclasses. An object must have animplementation for all of its methods. You need to create a subclass that provides animplementation for the abstract method.
A class abstract Vehicle might be specified as abstract to represent the general abstractionof a vehicle, as creating instances of the class would not be meaningful.
abstract class Vehicle {
int numofGears;String color;abstract boolean hasDiskBrake();abstract int getNoofGears();
}
Example of a shape class as an abstract class
abstract class Shape {
public String color;public Shape() {}public void setColor(String c) {
color = c;}public String getColor() {
return color;
-
7/27/2019 Java Tutorial Excelente Importante
18/211
}abstract public double area();
}
We can also implement the generic shapes class as an abstract class so that we can drawlines, circles, triangles etc. All shapes have some common fields and methods, but eachcan, of course, add more fields and methods. The abstract class guarantees that each shapewill have the same set of basic properties. We declare this class abstract because there is nosuch thing as a generic shape. There can only be concrete shapes such as squares, circles,triangles etc.
public class Point extends Shape {
static int x, y;public Point() {
x = 0;
y = 0;}public double area() {
return 0;}public double perimeter() {
return 0;}public static void print() {
System.out.println("point: " + x + "," + y);}public static void main(String args[]) {
Point p = new Point();
p.print();}}
Output
point: 0, 0
Notice that, in order to create a Point object, its class cannot be abstract. This means that allof the abstract methods of the Shape class must be implemented by the Point class.
The subclass must define an implementation for every abstract method of the abstractsuperclass, or the subclass itself will also be abstract. Similarly other shape objects can becreated using the generic Shape Abstract class.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In thesense, when a class extends an abstract class, it cant extend any other class.
-
7/27/2019 Java Tutorial Excelente Importante
19/211
Java Interface
In Java, this multiple inheritance problem is solved with a powerful construct calledinterfaces. Interface can be used to define a generic template and then one or more abstractclasses to define partial implementations of the interface. Interfaces just specify the method
declaration (implicitly public and abstract) and can only contain fields (which are implicitlypublic static final). Interface definition begins with a keyword interface. An interface likethat of an abstract class cannot be instantiated.
Multiple Inheritance is allowed when extending interfaces i.e. one interface can extendnone, one or more interfaces. Java does not support multiple inheritance, but it allows youto extend one class and implement many interfaces.
If a class that implements an interface does not define all the methods of the interface, thenit must be declared abstract and the method definitions must be provided by the subclassthat extends the abstract class.
Example 1: Below is an example of a Shape interface
interface Shape {
public double area();public double volume();
}
Below is a Point class that implements the Shape interface.
public class Point implements Shape {
static int x, y;public Point() {
x = 0;y = 0;
}public double area() {
return 0;}public double volume() {
return 0;}public static void print() {
System.out.println("point: " + x + "," + y);}public static void main(String args[]) {
Point p = new Point();p.print();
-
7/27/2019 Java Tutorial Excelente Importante
20/211
}}
Similarly, other shape objects can be created by interface programming by implementinggeneric Shape Interface.
Example 2: Below is a java interfaces program showing the power of interfaceprogramming in java
Listing below shows 2 interfaces and 4 classes one being an abstract class.Note: The method toStringin classA1 is an overridden version of the method defined in theclass named Object. The classesB1 and C1 satisfy the interface contract. But since theclass D1 does not define all the methods of the implemented interfaceI2, the class D1 isdeclared abstract.Also,i1.methodI2() produces a compilation error as the method is not declared inI1 or any of its
super interfaces if present. Hence a downcast of interface reference I1 solves the problemas shown in the program. The same problem applies to i1.methodA1(), which is againresolved by a downcast.
When we invoke the toString() method which is a method of an Object, there does not seemto be any problem as every interface or class extends Object and any class can override thedefault toString() to suit your application needs. ((C1)o1).methodI1() compilessuccessfully, but produces a ClassCastException at runtime. This is because B1 does nothave any relationship with C1 except they are siblings. You cant cast siblings into one
another.
When a given interface method is invoked on a given reference, the behavior that resultswill be appropriate to the class from which that particular object was instantiated. This isruntime polymorphism based on interfaces and overridden methods.
interface I1 {
void methodI1(); // public static by default}
interface I2 extends I1 {
void methodI2(); // public static by default}
class A1 {
public String methodA1() {String strA1 = "I am in methodC1 of class A1";return strA1;
}public String toString() {
return "toString() method of class A1";
-
7/27/2019 Java Tutorial Excelente Importante
21/211
}}
class B1 extends A1 implements I2 {
public void methodI1() {
System.out.println("I am in methodI1 of class B1");}public void methodI2() {
System.out.println("I am in methodI2 of class B1");}
}
class C1 implements I2 {
public void methodI1() {System.out.println("I am in methodI1 of class C1");
}public void methodI2() {
System.out.println("I am in methodI2 of class C1");
}}
// Note that the class is declared as abstract as it does not// satisfy the interface contractabstract class D1 implements I2 {
public void methodI1() {}// This class does not implement methodI2() hence declared abstract.
}
public class InterFaceEx {
public static void main(String[] args) {I1 i1 = new B1();i1.methodI1(); // OK as methodI1 is present in B1// i1.methodI2(); Compilation error as methodI2 not present in I1// Casting to convert the type of the reference from type I1 to typ((I2) i1).methodI2();I2 i2 = new B1();i2.methodI1(); // OKi2.methodI2(); // OK// Does not Compile as methodA1() not present in interface referen// String var = i1.methodA1();// Hence I1 requires a cast to invoke methodA1String var2 = ((A1) i1).methodA1();
System.out.println("var2 : " + var2);String var3 = ((B1) i1).methodA1();System.out.println("var3 : " + var3);String var4 = i1.toString();System.out.println("var4 : " + var4);String var5 = i2.toString();System.out.println("var5 : " + var5);I1 i3 = new C1();String var6 = i3.toString();
-
7/27/2019 Java Tutorial Excelente Importante
22/211
System.out.println("var6 : " + var6); // It prints the Object toStmethod
Object o1 = new B1();// o1.methodI1(); does not compile as Object class does not define// methodI1()// To solve the probelm we need to downcast o1 reference. We can d
// in the following 4 ways((I1) o1).methodI1(); // 1((I2) o1).methodI1(); // 2((B1) o1).methodI1(); // 3/*** B1 does not have any relationship with C1 except they are "sibl** Well, you can't cast siblings into one another.**/
// ((C1)o1).methodI1(); Produces a ClassCastException}
}
Output
I am in methodI1 of class B1I am in methodI2 of class B1I am in methodI1 of class B1I am in methodI2 of class B1var2 : I am in methodC1 of class A1var3 : I am in methodC1 of class A1var4 : toString() method of class A1var5 : toString() method of class A1
var6 : C1@190d11I am in methodI1 of class B1I am in methodI1 of class B1I am in methodI1 of class B1
-
7/27/2019 Java Tutorial Excelente Importante
23/211
Interface vs Abstract Class
Interface vs Abstract Class
Taken from http://interview-questions-java.com/abstract-class-interface.htm
1. Abstract class is a class which contain one or more abstract methods, which has to beimplemented by sub classes. An abstract class can contain no abstract methods also i.e.abstract class may contain concrete methods. A Java Interface can contain only methoddeclarations and public static final constants and doesnt contain their implementation. Theclasses which implement the Interface must provide the method definition for all themethods present.
2. Abstract class definition begins with the keyword abstract keyword followed by Class
definition. An Interface definition begins with the keyword interface.
3. Abstract classes are useful in a situation when some general methods should beimplemented and specialization behavior should be implemented by subclasses. Interfacesare useful in a situation when all its properties need to be implemented by subclasses
4. All variables in an Interface are by default - public static final while an abstract class canhave instance variables.
5. An interface is also used in situations when a class needs to extend an other class apartfrom the abstract class. In such situations its not possible to have multiple inheritance ofclasses. An interface on the other hand can be used when it is required to implement one ormore interfaces. Abstract class does not support Multiple Inheritance whereas an Interface
supports multiple Inheritance.
6. An Interface can only have public members whereas an abstract class can contain privateas well as protected members.
7. A class implementing an interface must implement all of the methods defined in theinterface, while a class extending an abstract class need not implement any of the methodsdefined in the abstract class.
8. The problem with an interface is, if you want to add a new feature (method) in itscontract, then you MUST implement those method in all of the classes which implement
that interface. However, in the case of an abstract class, the method can be simplyimplemented in the abstract class and the same can be called by its subclass
9. Interfaces are slow as it requires extra indirection to to find corresponding method in inthe actual class. Abstract classes are fast
10.Interfaces are often used to describe the peripheral abilities of a class, and not its centralidentity, E.g. an Automobile class might
http://interview-questions-java.com/abstract-class-interface.htmhttp://interview-questions-java.com/abstract-class-interface.htmhttp://interview-questions-java.com/abstract-class-interface.htm -
7/27/2019 Java Tutorial Excelente Importante
24/211
implement the Recyclable interface, which could apply to many otherwise totally unrelatedobjects.
Note: There is no difference between a fully abstract class (all methods declared as abstractand all fields are public static final) and an interface.
Note: If the various objects are all of-a-kind, and share a common state and behavior, thentend towards a common base class. If all theyshare is a set of method signatures, then tend towards an interface.
Similarities:
Neither Abstract classes nor Interface can be instantiated.
List ofobjects that implement this interface can be sorted automatically by sort method ofthe list interface. This interface has compareTo() method that is used by the sort() method
of the list.
In this code Employee class is implementing Comparable interface and have methodcompareTO(). ComparableDemo.java is showing the use of this interface. This class firstmakes a list of objects of type Employee and call sort method of java.util.Collections,which internally uses compareTo() method of Employee class and sort the list accordingly.
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;double Sal;static int i;
public Employee() {EmpID = i++;Ename = "dont know";Sal = 0.0;
}
public Employee(String ename, double sal) {EmpID = i++;Ename = ename;
Sal = sal;}
public String toString() {return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal"
+ Sal;}
public int compareTo(Object o1) {if (this.Sal == ((Employee) o1).Sal)
-
7/27/2019 Java Tutorial Excelente Importante
25/211
return 0;else if ((this.Sal) > ((Employee) o1).Sal)
return 1;else
return -1;}
}
ComparableDemo.java
importjava.util.*;
public class ComparableDemo{
public static voidmain(String[] args) {
List ts1 = new ArrayList();ts1.add(new Employee ("Tom",40000.00));ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));ts1.add(new Employee ("Chris",70000.00));Collections.sort(ts1);Iterator itr = ts1.iterator();
while(itr.hasNext()){Object element = itr.next();System.out.println(element + "\n");
}
}}
Output:
EmpID 1Ename HarrySal20000.0
EmpID 0Ename TomSal40000.0
EmpID 2Ename Maggie
Sal50000.0
EmpID 3Ename ChrisSal70000.0
-
7/27/2019 Java Tutorial Excelente Importante
26/211
Java IntroductionIn this lesson of the Java tutorial, you will learn...
1. About the Java Runtime Environment and how a Java program is created, compiled, andrun
2. How to download, install, and set up the Java Development Kit Standard Edition3. How to create a simple Java program
Conventions in These Notes
Code is listed in a monospace font, both for code examples and for Java keywordsmentioned in the text.
The standard Java convention for names is used:
class names are listed with an initial uppercase letter. variable and function names are listed with an initial lowercase letter. the first letters of inner words are capitalized (e.g., maxValue).
For syntax definitions:
terms you must use as is are listed in normal monospace type. terms that you must substitute for, either one of a set of allowable values, or a name of
your own, or code, listed in italics.
the following generic terms are used - you must substitute an appropriate term.
GenericTerms
Substitution Options
access An access word from: public, protected, private, or it can be omitted
modifiersone or more terms that modify a declaration; these include the access terms as well
as terms like: static, transient, or volatile
dataTypeA data type word; this can be a primitive, such as int, or the name of a class, such as
Object; variants of this include: returnType and paramType
variableName The name of a variable; variants on this include paramName and functionName
ClassName
The name of a class; there will be variants of this used for different types of
examples, such as: BaseClassName, DerivedClassName, InterfaceName, and
ExceptionClassName
-
7/27/2019 Java Tutorial Excelente Importante
27/211
Generic
TermsSubstitution Options
code executable code goes here
. . . in an example, omitted code not related to the topic
The Java Environment - Overview
A Java program is run differently than a traditional executable program.
Traditional programs are invoked through the operating system.
they occupy their own memory space. they are tracked as an individual process by the OS.
Traditional programs are compiled from source code into a machine and OS-specific binaryexecutable file.
to run the program in different environments, the source code would be compiled for thatspecific target environment.
When you run a Java program, the OS is actually running theJava Runtime Engine, orJRE,as an executable program; it processes your compiled code through theJava VirtualMachine (usually referred to as theJVM).
A Java source code file is compiled into a bytecode file.
you can consider bytecode as a sort of generic machine language. the compiled bytecode is read by the JVM as a data file. the JVM interprets the bytecode at runtime, performing a final mapping of bytecode to
machine language for whatever platform it is running on.
thus, Java programs are portable - they can be written in any environment, compiled inany environment, and run in any environment (as long as a JVM is available for that
environment).
the JVM manages its own memory area and allocates it to your program as necessary.
although this involves more steps at runtime, Java is still very efficient, much more so thancompletely interpreted languages like JavaScript, since the time-consuming parsing of the
source code is done in advance.
Writing a Java Program
Java source code is written in plain text, using a text editor.
-
7/27/2019 Java Tutorial Excelente Importante
28/211
this could range from a plain text editor like Notepad, to a programmers' editor such asTextPad, EditPlus, or Crimson Editor, to a complex integrated development environment
(IDE) like NetBeans, Eclipse, or JDeveloper
the source code file should have a .java extension.The javac compiler is then used to compile the source code into bytecode.
javac MyClass.java
the bytecode is stored in a file with an extension .class bytecode is universal - one bytecode file will run on any supported platform.
You then run the java runtime engine, which will then interpret the bytecode to execute theprogram.
java MyClass
the executable program you are running is: java. the class name tells the JVM what class to load and run the main method for. you must have a JVM made specifically for your hardware/OS platform.
-
7/27/2019 Java Tutorial Excelente Importante
29/211
Obtaining The Java Environment
You can download the SDK (software development kit) including the compiler and runtimeengine from Sun at:http://java.sun.com/javase.
look for the download of J2SE 1.6.0.10 (or the latest release version).You can also download the API documentation and even the source code.
the documentation lists all the standard classes in the API, with their data fields andmethods, as well as other information necessary to use the class
you can view the docs online, but it is worth downloading it so that you don't have to beconnected to the internet to use it
Setting up your Java Environment
Java programs are compiled and run from an operating system prompt, unless you haveinstalled an IDE that will do this for you directly.
if you create an applet, this would run inside a web page in a browser.After you have installed the JDK, you will need to set at least one environment variable inorder to be able to compile and run Java programs.
For more complex projects that pull together elements form different sources, you must setan additional environment variable or two.
a PATH environment variable enables the operating system to find the JDK executableswhen your working directory is not the JDK's binary directory
CLASSPATH is Java's analog to PATH, the compiler and JVM use it to locate Java classeso often you will not need to set this, since the default setting is to use the JDK's
library jar file and the current working directory
o but, if you have additional Java classes located in another directory (a third-partylibrary, perhaps), you will need to create a classpath that includes not only that
library, but the current working directory as well (the current directory is
represented as a dot)
many IDE's and servers expect to find a JAVA_HOME environment variableo this would be the JDK directory (the one that contains bin and lib)o the PATH is then set from JAVA_HOME plus \bino this makes it easy to upgrade your JDK, since there is only one entry you will need
to change
Best Practice: Setting PATH from JAVA_HOME
http://java.sun.com/j2sehttp://java.sun.com/j2sehttp://java.sun.com/j2sehttp://java.sun.com/j2se -
7/27/2019 Java Tutorial Excelente Importante
30/211
The procedure to permanently set the environment variables varies slightly from oneversion of Windows to another; the following will work in many, including Windows XP.The process for Vista is similar, but slightly different:
1. right-click on My Computer2. choose Properties3. select theAdvancedtab4. click the Environment Variables button at the bottom5. check both the Userand System variable lists to see if JAVA_HOME or PATH already exist6. if JAVA_HOME exists, check to see that it matches your most recent JDK (or the one you
wish to use)
1. it is probably better to set this as a System variable2. if it exists, click Edit, if not, clickAdd3. for the variable name, enter JAVA_HOME4. for the value, enter your JDK directory, such as Error. This text should not be
shown. Please email [email protected] to report it: C:\Program
Files\Java\jdk1.5.0_14
note that the space in the name can sometimes cause problems one solution is to put quote marks around the entry, as in " C:\Program
Files\Java\jdk1.5.0_14 Error. This text should not be shown. Please email
[email protected] to report it: C:\Program
Files\Java\jdk1.5.0_14"
an even better solution would be to use the 8-character form of thedirectory name, such as C:\Progra~1\Java\jdk1.5.0_14 Error. This
text should not be shown. Please email [email protected] to
report it: C:\Progra~1\Java\jdk1.5.0_14 (you can check if this works in
your system by typing it into the address bar of a My Computerwindow)
-
7/27/2019 Java Tutorial Excelente Importante
31/211
7. for PATH, again select eitherAddor Edito you could do this either as a Uservariable or a System variableo if there isn't already a JDK bin directory mentioned in the PATH, it will work as a
Uservariable
o if there is already a JDK mentioned, you would want to ensure that this new entrypreceded the existing entry, so you would edit that variable
o note that if the existing entry was created using JAVA_HOME, then we are alreadyset correctly
o if you "prepend" an entry to PATH , it will be found first, and therefore supercedeany other directory - if you append to path, your directory won't be found if an
earlier entry JDK entry exists (the following image shows a prepend)
o also note that System variables precede Uservariables, so they will be found first
-
7/27/2019 Java Tutorial Excelente Importante
32/211
Setting environment variables from a command prompt
If you set the variables from a command prompt, they will only hold for that session, butyou could create a batch file that you could run each time you open a command prompt
window.
To set the PATH from a command prompt or batch file:
set PATH=C:\Progra~1\Java\jdk1.6.0_10\bin;%PATH%
If you need to set the CLASSPATH:
set CLASSPATH=.;%CLASSPATH%
early version s of the JDK required you to include the JDK's lib directory in the CLASSPATH;this is no longer necessary
note that UNIX environments use $PATH and $CLASSPATH instead of %PATH% and%CLASSPATH%, and that the path element separator is a colon instead of a semicolon
Creating a Class That Can Run as a Program
The main() Method
In order to run as a program, a class must contain a method named main, with a particularargument list.
this is similar to the C and C++ languages.The definition goes inside your class definition, and looks like:
public static void main(String[] args) {(code goes here)}
-
7/27/2019 Java Tutorial Excelente Importante
33/211
it must be public, because it will be called from outside your class (by the JVM). the static keyword defines an element (could be data or functional) that will exist
regardless of whether an object of the class has been instantiated technically, even though
you may run the class as a program, that doesn't mean that any object of that class is ever
instantiated - you must instantiate one explicitly if you want to have one.
the String[] args parameter list states that there will be an array of String objects given tothe method - these are the command line arguments.
to run the program, use the following from the command line: java ClassName
for example, if we had an executable class called Hello, in a file called Hello.java that
compiled to Hello.class, you could run it with:
java Hello
Useful Stuff Necessary to go Further
System.out.println()
In order to see something happen, we need to be able to print to the screen.
There is a System class that is automatically available when your program runs (everythingin it is static).
it contains, among other things, input and output streams that match stdin, stdout, andstderr (standard output, standard input, and standard error).
System.out is a static reference to the standard output stream.
As an object, System.out contains a println(String) method that accepts a String object, andprints that text onto the screen, ending with a newline (linefeed).
there is also a print(String) method that does not place a newline at the end.You can print a String directly, or you can build one from pieces.
it is worth noting that a String will automatically be created from a quote-delimited seriesof characters
values can be appended to a String by using the + sign; if one item is a String or quote-delimited series of characters, then the rest can be any other type of data.
Exercise: First Java Program
Duration: 5 to 15 minutes.
-
7/27/2019 Java Tutorial Excelente Importante
34/211
1. Create a file called Hello.java.2. Enter the following code:3. public class Hello {4. public static void main(String[] args) {5. System.out.println("Hello World");6. }
}
7. Save the file.8. In a command prompt window, change to the directory where Hello.java is stored and
type the following:
javac Hello.java
1. A prompt on the next line without any error messages indicates success.9. Type:
java Hello
10.Press Enter.1. You should see the message Hello World print in the window.
Code Explanation
public class Hello
all Java code must be within a class definition. a class defines a type of object. a public class can be accessed by any other class. a public class must be in its own file, whose name is the name of the class, plus a dot and
an file extension of java (e.g., Hello.java ) { . . .
}
curly braces denote a block of code (the code inside the braces). code within braces usually belongs to whatever immediately precedes them
public static void main(String[] args) {
words followed by parentheses denote a function. to be executable by itself, a class must have a function defined in this fashion; the name
main means that execution will start with the first step of this function, and will end whenthe last step is done.
it is public because it needs to be executed by other Java objects (the JVM itself is arunning Java program, and it launches your program and calls its main function).
it is static because it needs to exist even before one of these objects has been created. it does not return an answer when it is done; the absence of data is called void. the String[] args represents the additional data that might have been entered on the
command line.
-
7/27/2019 Java Tutorial Excelente Importante
35/211
System.out.println("Hello World!");
System is an class within the JVM that represents system resources. it contains an object called out, which represents output to the screen (what many
environments call standard out).
note that an object's ownership of an element is denoted by using the name of the object,a dot, and then the name of the element.
out in turn contains a function, println, that prints a line onto the screen (and appends anewline at the end).
a function call is denoted by the function name followed by parentheses; any informationinside the parentheses is used as input to the function (called arguments or parameters to
the function).
the argument passed to println() is the string of text "Hello World!". note that the statement ends in a semicolon (as all do Java statements).
Using the Java Documentation
Sun provides extensive documentation of the API (library of available classes). Thedocument ion for version 6 is available athttp://java.sun.com/javase/6/docs/api/
If you view that page, you will see a list of classes on the left as hyperlinks. Clicking a classname will bring up the documentation for that class on the right.
For example, click on System. The page on the right contains documentation on theelements of the class, categorized by type of element (there are links at the top for fields,constructors, methods, etc.).
Try to locate the out field - note that the field types, parameter types and return types arehyperlinked, and that out is a PrintStream. Click that, and find the println methods in a tablewith short descriptions. Select one to see the detailed description. The multiple versions arean example ofmethod overloading, which we will cover in an upcoming lesson. Anotherlesson will cover documenting your own classes with the same tool that created thisdocumentation.
In this lesson of the Java tutorial, you have learned:
Java Introduction Conclusion
1. About the Java Runtime Environment2. How to download, install, and set up the Java Development Kit Standard Edition3. How to create a simple Java program
http://java.sun.com/javase/6/docs/api/http://java.sun.com/javase/6/docs/api/http://java.sun.com/javase/6/docs/api/http://java.sun.com/javase/6/docs/api/ -
7/27/2019 Java Tutorial Excelente Importante
36/211
Java BasicsIn this lesson of the Java tutorial, you will learn...
1. Understand Java's basic syntax rules, including statements, blocks, and comments2. Declare variables and construct statements using variables and literal (constant) values3. Become familiar with the primitive data types, as well as the String class.4. Understand many of Java's operators and the concept of operator precedence.5. Understand the rules that apply when data is converted from one type to another.6. Declare, write, and use simple methods
Basic Java Syntax
General Syntax Rules
Java is case-sensitive
main(), Main(), and MAIN() would all be different methodsThere are a limited number of reserved words that have a special meaning within Java.
you may not use these words for your own variables or methods examples: public, void, static, do, for, while, if
Most keyboard symbol characters (the set of characters other than alphabetic or numeric)have a special meaning
Names may contain alphabetic characters, numeric characters, currency characters, andconnecting characters such as the underscore ( _ ) character
names may not begin with a numeric character note that the set of legal characters draws from the entire Unicode character set also note that it is probably impossible to write a succinct set of rules about what are valid
characters, other than to say a character, that when passed to
Character.isJavaIdentifierPart(char ch), results in a true value
The compiler parses your code by separating it into individual entities:
names (of classes, variables, and methods) command keywords single or compound symbols (compound symbols are when an operation is signified by a
two-symbol combination)
these entities are called tokens or symbols in computer science jargon
-
7/27/2019 Java Tutorial Excelente Importante
37/211
Tokens may be separated by spaces, tabs, carriage returns, or by use of an operator(such as+, -, etc.)
since names may not contain spaces, tabs, or carriage returns, or operator characters,these characters imply a separation of what came before them from what comes after
them
Extra whitespace is ignored
once the compiler knows that two items are separate, it ignores any additional separatingwhitespace characters (spaces, tabs, or carriage returns)
Java Statements
A statement:
one step of code, which may take more than one line ends with a semicolon (the ; character) it is OK to have multiple statements on one line
Program execution is statement by statement, one statement at a time
from top to bottom (if more than one statement on a line, left to right)Within a statement, execution of the individual pieces is not necessarily left to right
there are concepts called operator precedence and associativitythat determine the orderof operations within a statement
Blocks of Code
A block of code:
is enclosed in curly braces - start with { and end with } consists of zero, one, or more statements behaves like a single statement to the outside world a complete method is a block blocks may be nested - containing one or more blocks inside generally, blocks belong to whatever comes before them (although it is perfectly OK to
create a block that does not, this is almost never done)
Example
-
7/27/2019 Java Tutorial Excelente Importante
38/211
If you want, go ahead and modify your Hello World program to match this example
Comments
A comment:
is additional non-executable text in a program, used to document code may also be used to temporarily disable a section of code (for debugging)
Block comment: preceded by /* and followed by */
may not be nested may be one or more lines /* this is a block comment * asterisk on this line not necessary, but looks nice
*/
may span part of a line, for example, to temporarily disable part of a statement:x = 3 /* + y */ ;
Comment to end of line: preceded by //
ends at the end of that line may be nested inside block comments y = 7; /* * temporarily disable this line which has a comment to end of line x = 3 + y; // add 3 for some reason
*/
Java specifies a third type of comment, thejavadoc comment
-
7/27/2019 Java Tutorial Excelente Importante
39/211
Java contains a self-documentation utility,javadoc, which builds documentation fromcomments within the code
javadoc comments begin with /** and end with */ they only work as javadoc comments when placed at specific locations in your code
(immediately above anything documentable - the class itself and its members), otherwise
they are treated as ordinary comments
/** Represents a person, with a first nanme and last name. */ public class Person { /** The person's first name */ public String firstName; /** The person's last name */ public String lastName; }
Variables
Variables store data that your code can use
There are two fundamental categories of variables,primitive data and references
with primitive data, the compiler names a memory location and uses to store the actualdata - numeric values such as integers, floating point values, and the code values of single
individual text characters are stored as primitives
with references, the data is accessed indirectly - the compiler selects a memory location,associates it with the variable name, and stores in it a value that is effectively the memory
address of the actual data - in Java, all objects and arrays are stored using references
In the diagram below, the boxes are areas in memory:
-
7/27/2019 Java Tutorial Excelente Importante
40/211
Declaring Variables
Variables must be declaredbefore they are used
A declaration informs the compiler that you wish to:
create an identifierthat will be accepted by the compiler within a section of code (exactlywhat that section is depends on how and where the variable is declared; that is the
concept ofscope, which will be addressed later)
associate that identifier with a specified type of data, and enforce restrictions related tothat in the remainder of your code
create a memory location for the specified type of data associate the identifier with that memory location
Java uses many specific data types; each has different properties in terms of size requiredand handling by the compiler
the declaration specifies the name and datatype generally the declaration also defines the variable, meaning that it causes the compiler to
allocate storage space in memory of the requested type's size
a declaration may also assign in initial value (to initialize the variable) multiple variables of the same type can be declared in a comma-separated list
-
7/27/2019 Java Tutorial Excelente Importante
41/211
Code Effect
int a; declares the name a to exist, and allocates a memory location to hold a 32-bit integer
int a = 0;same as above, and also assigns an initial value of 0
int a = 0, b, c =
3; declares three integer variables and initializes two of them
Note that different languages have different rules regarding trying to read data fromvariables that have not been initialized
some languages just let the value be whatever happened to be in that memory locationalready (from some previous operation)
some languages initialize automatically to 0 some languages give a compiler or runtime error Java uses both of the last two: local variables within methods must be initialized before
attempting to use their value, while variables that are fields within objects are
automatically set to zero
Advanced Declarations
Local variables, fields, methods, and classes may be given additional modifiers; keywordsthat determine any special characteristics they may have
any modifiers must appear first in any declaration, but multiple modifiers may appear inany order
Keyword Usage Comments
final
local
variables,
fields,
methods,
classes
the name refers to a fixed item that cannot be changed
for a variable, that means that the value cannot be changed
for a method, the method cannot be overridden whenextending the class
a final field does not, however, have to be initializedimmediately; the initial assignment may be done once duringan object's construction
static
fields,
methods,
inner classes
only for fields and methods of objects
one copy of the element exists regardless of how many
-
7/27/2019 Java Tutorial Excelente Importante
42/211
Keyword Usage Comments
instances are created
the element is created when the class is loaded
transient fields the value of this element will not be saved with this objectwhen serialization is used (for example, to save a binary objectto a file, or send one across a network connection)
volatile fieldsthe value of this element may change due to outside influences(other threads), so the compiler should not perform anycaching optimizations
public,
protected,
private
fields,
methods
classes
specifies the level of access from other classes to this element- covered in depth later
abstractmethods,
classes
specifies that a method is required for a concrete extension ofthis class, but that the method will not be created at this levelof inheritance - the class must be extended to realize themethod
for a class, specifies that the class itself may not beinstantiated; only an extending class that is not abstract may beinstantiated (a class must be abstract if one or more of it'smethods is abstract) - covered in depth later
native methodsthe method is realized in native code (as opposed to Java code)- there is an external tool in the JDK for mapping functions
from a DLL to these methods
strictfpmethods,
classes
for a method, it should perform all calculations in strictfloating point (some processors have the ability to performfloating point more accurately by storing intermediate resultsin a larger number of bits than the final result will have; whilemore accurate, this means that the results might differ acrossplatforms)
for a class, this means that all methods are strictfp
synchronizedmethods,
code blocksno synchronized code may be accessed from multiple threads
for the same object instance at the same time
Data
Primitive Data Types
-
7/27/2019 Java Tutorial Excelente Importante
43/211
Theprimitive data types store single values at some memory location that the compilerselects and maps to the variable name you declared
primitive values are not objects - they do not have fields or methods
A primitive value is stored at the named location, while an object is accessed using areference
an object reference variable does not store the object's data directly - it stores a referenceto the block of data, which is somewhere else in memory (technically, the reference stores
the memory address of the object, but you never get to see or use the address)
Primitives Data Types
Primitive
Type
Storage
SizeComments
boolean 1 bitnot usable mathematically, but can be used with logical and bitwise
operators
char 16 bits unsigned, not usable for math without converting to int
byte 8 bits signed
short 16 bits signed
int 32 bits signed
long 64 bits signed
float 32 bits signed
double 64 bits signed
void None not really a primitive, but worth including here
Object Data TypesObjects can be data, which can be stored in variables, passed to methods, or returned frommethods.
References
-
7/27/2019 Java Tutorial Excelente Importante
44/211
As we will see later, objects are stored differently than primitives. An object variable storesa reference to the object (the object is located at some other memory location, and thereference is something like a memory address)
Text Strings
A sequence of text, such as a name, an error message, etc., is known as astring
In Java, the String class is used to hold a sequence of text characters
A String object:
is accessed through a reference, since it is an object has a number of useful methods, for case-sensitive or case-insensitive comparisons,
obtaining substrings, determining the number of characters, converting to upper or lower
case, etc.
is immutable; that is, once created it cannot be changed (but you can make your variablereference a different String object at any time)
Literal Values
A value typed into your code is called a literalvalue
The compiler makes certain assumptions about literals:
true and false are literal boolean values null is a literal reference to nothing (for objects) a numeric value with no decimal places becomes an int, unless it is immediately assigned
into a variable of a smaller type and falls within the valid range for that type
a value with decimal places becomes a double to store a text character, you can put apostrophes around the character
Code Effect
char e = 'X'; creates a 16-bit variable to hold the Unicode value for the uppercase X character
You can add modifiers to values to instruct the compiler what type of value to create (note
that all the modifiers described below can use either uppercase or lowercase letters)
Modifying prefixes enable you to use a different number base
Prefix Effect
0X or0x a base 16 value; the extra digits can be either uppercase or lowercase, as in char c = 0x1b;
-
7/27/2019 Java Tutorial Excelente Importante
45/211
Prefix Effect
0 a base 8 value, as in int i = 0765;
note: using these prefixes will always result in number that is considered positive (so that0x7F for a byte would be OK, but 0x80 would not, since the latter would have a value of128, outside the range of byte)
also note that a long value would need the L modifier as discussed belowModifying suffixes create a value of a different type than the default
Suffix Effect
L orl
a long value (uses 64 bits of
storage), as in long l =
1234567890123456L;
note: an int value will always implicitly be promoted to a long
when required, but the reverse is not true; the above
notation is necessary because the literal value is larger than
32 bits
F orf a float value, as in float f = 3.7F;
Escape Sequences for Character Values
There are a number ofescape sequences that are used for special characters
Escape
SequenceResulting Character
\b backspace
\f form feed
\n a linefeed character - note that it produces exactly one character, Unicode 10(\u000A in hex)
\r a carriage return
\t a tab
-
7/27/2019 Java Tutorial Excelente Importante
46/211
Escape
SequenceResulting Character
\" a quote mark
\' an apostrophe
\\ a backslash
\uNNNNa Unicode value, where N is a base 16 digit from 0 through F; valid values are
\u0000 through \uFFFF
\NNN a value expressed in octal; ranging from \000 to \377
The escape sequences can either be used for single characters or within strings of text
char c = '\u1234';System.out.println("\t\tHello\n\t\tWorld");
Constants and the final keyword
Java has a means for defining constant values
like variables in that they have names, but not changeable once setIf a variable is declared as final, it cannot be changed
even though the variable's value is not changeable once a value has been established, youare allowed to set a unique value once
local variables within methods may be declared as final their values may be set in an explicit initialization, in a separate line of code, or, for
method parameters, as the value passed in when the method is called
fields within a class may be declared as final their values may be set in an explicit initialization, in a separate line of code within an
initialization block, or in a constructor
Fields of a class may be declared as public static final - that way they are available to other
classes, but cannot be changed by those other classes
an example is Math.PIClasses and methods may also be marked as final, we will cover this later
Code Sample: Java-Basics/Demos/FinalValues.java
-
7/27/2019 Java Tutorial Excelente Importante
47/211
import java.io.*;public class FinalValues {final int f1 = 1;final int f2;{f2 = 2;
}
final int f3;public FinalValues(int i) {f3 = i;final int f4 = i;System.out.println("In constructor, f4 = " + f4);
}public void useFinalParameter(final int f5) {System.out.println("f5 = " + f5);
}public void printAll() {System.out.println("f1 = " + f1);System.out.println("f2 = " + f2);System.out.println("f3 = " + f3);
}
public static void main(String[] args) {FinalValues fv = new FinalValues(3);fv.useFinalParameter(5);fv.printAll();
}}
Mathematics in Java
Looks and behaves like algebra, using variable names and math symbols:
int a, b, c, temp;a = b/c + temp;b = c * (a - b);
Basic Rules
what goes on the left of the = sign is called an lvalue; only things that can accept a valuecan be an lvalue (usually this means a variable name - you can't have a calculation like a +
b in front of the equal sign);
math symbols are known as operators; they include:Operator Purpose (Operation Performed)
+ for addition
- for subtraction
-
7/27/2019 Java Tutorial Excelente Importante
48/211
Operator Purpose (Operation Performed)
* for multiplication
/ for division
% for modulus (remainder after division)
( and) for enclosing a calculation
note that integer division results in an integer - any remainder is discarded
Expressions
An expression is anything that can be evaluated to produce a value
every expression yields a valueExamples (note that the first few of these are not complete statements):
Two simple expressions
a + 55/c
An expression that contains another expression inside, the (5/c) part
b + (5/c)
A statement is an expression; this one that contains another expression inside - the b + (5/c)part, which itself contains an expression inside it (the 5/c part)
a = b + (5/c);
Since an assignmentstatement (using the = sign) is an expression, it also yields a value (thevalue stored is considered the result of the expression), which allows things like this:
d = a = b + (5/c);
the value stored in a is the value of the expression b + (5/c) since an assignment expression's value is the value that was assigned, the same value is
then stored in d
the order of processing is as follows:1. retrieve the value of b2. retrieve the 5 stored somewhere in memory by the compiler3. retrieve the value of c
-
7/27/2019 Java Tutorial Excelente Importante
49/211
4. perform 5 / c5. add the held value of b to the result of the above step6. store that value into the memory location for a7. store that same value into the memory location for d
Here is a moderately complicated expression; let's say that a, b, and c are all doublevariables, and that a is 5.0, b is 10.0, and c is 20.0:
d = a + b * Math.sqrt(c + 5);
since the c + 5 is in parentheses, the compiler creates code to evaluate that first but, to perform the c + 5 operation, both elements must be the same type of data, so the
thing the compiler creates is a conversion for the 5 to 5.0 as a double
d = a + b * Math.sqrt(c + 5.0);
then the compiler creates code to evaluate 20.0 + 5.0 (at runtime it would become 25.0),reducing the expression to:
d = a + b * Math.sqrt(25.0);
next, the compiler adds code to call the Math.sqrt method to evaluate its result, which willbe 5.0, so the expression reduces to:
d = a + b * 5.0;
note: the evaluated result of a method is known as the return value, or value returned multiplication gets done before addition, the compiler creates that code next, to reduce
the expression to:
d = a + 50.0;
then the code will perform the addition, yieldingd = 55.0;
and finally, the assignment is performed so that 55.0 is stored in dAs implied by the examples we have seen so far, the order of evaluation of a complexexpression is not necessarily from left to right
there is a concept called operator precedence that defines the order of operations
Operator Precedence
Operator precedence specifies the order of evaluation of an expression
-
7/27/2019 Java Tutorial Excelente Importante
50/211
every language has a "table of operator precedence" that is fairly long and complexMost languages follow the same general rules
anything in parentheses gets evaluated before the result is related to what is outside theparentheses
multiply or divide get done before add and subtractExample
in the expression a = b + 5/c, the 5/c gets calculated first, then the result is added to b,then the overall result is stored in a
the equal sign = is an operator; where on the table do you think it is located?The basic rule programmers follow is: when in doubt about the order of precedence, useparentheses
Try the following program:
Code Sample: Java-
Basics/Demos/ExpressionExample.java
public class ExpressionExample {public static void main(String[] args) {double a = 5.0, b = 10.0, c = 20.0;System.out.println("a+b is " + (a + b));System.out.println("a+b/c is " + (a + b / c));System.out.println("a*b+c is " + (a * b + c));
System.out.println("b/a+c/a is " + (b / a + c / a));}
}
Multiple Assignments
Every expression has a value. For an assignment expression, the value assigned is theexpression's overall value. This enables chaining of assignments :
x = y = z + 1; is the same as y = z + 1; x = y;
i = (j = k + 1)/2; is the same as j = k + 1; i = j/2;
Quite often, you may need to calculate a value involved in a test, but also store the value forlater use
double x;if ( (x = Math.random()) < 0.5 ) {System.out.println(x);
-
7/27/2019 Java Tutorial Excelente Importante
51/211
}
You might wonder why not just generate the random number when we declare x? In thiscase, that would make sense, but in a loop the approach shown above might be easier
generates the random number and stores it in x as an expression, that results in the same value, which is then tested for less than 0.5, and
the loop body executes if that is true
the value of x is then available within the block after the loop body executes, another random number is generated as the process repeats
It is usually not necessary to code this way, but you will see it often
Order of Evaluation
The order of operand evaluation is always left to right, regardless of the precedence of the
operators involved
Code Sample: Java-Basics/Demos/EvaluationOrder.java
public class EvaluationOrder {public static int getA() {System.out.println("getA is 2");return 2;
}public static int getB() {System.out.println("getB is 3");return 3;
}public static int getC() {System.out.println("getC is 4");return 4;
}public static void main(String[] args) {int x = getA() + getB() * getC();System.out.println("x = " + x);
}}
Code Explanation
the operands are first evaluated in left to right order, so that the functions are called inthe order getA(), then getB(), and, lastly, getC()
but, the returned values are combined together by multiplying the results of getB() andgetC(), and then adding the result from getA()
Bitwise Operators
Java has a number of operators for working with the individual bits within