¿Tienes una cuenta? identificate: Usuario Contraseña o puedes obtener una gratis.

[ Escribo sobre... ]

Historia Túpac Amaru Shakur, 1ra. Parte

sáb 10 de septiembre, 2005 - 18:47

Estado de ánimo: X
Seguridad de entrada: PUBLICO

El verdadero nombre de Tupac era Lisane Parish Crooks, pero el se lo cambio a Túpac amaru (el significado de Túpac es “Shining Serpent” o Serpiente Luminosa)en honor al indígena revolucionario.

El nacio en Brooklin en el estado de Nueva York, el 16 de Julio del 71, su madre Alice Faye Williams (quien despues se cambio el nombre a Afeni Shakur)y padre (William Garland) fueron pertenecientes al grupo anti-racial “Black Panther” (Pantera Negra), entre los 60’s y 70´s.

Su madre fue encarcelada a los 21 años de edad por acusasiones en su contra por la planeacion de ataques a bancos y almacenes pequeños, la liberaron 2 meses antes de dar a luz a Lisane que desde pequeño ya se hacia llamar Túpac.

De niño tambien se le conocia como el “Black Prince” (Principe Negro), cuando el tenia dos años nacio su hermanastra Sekyiwa Shakur, hija de Mutula Shakur, a quien pusieron bajo prision antes de que esta naciera por robo de auto a mano armada. La familia de Túpac decidio mudarse al Bronx.

A los 12 años ingresa a la 127th Street Ensemble de Harlem en donde empesaria su aprendizaje en la actuación. En su adolescencia se muda de nuevo con su famila a Baltimore en donde comienza a escribir su poesía y canciones, su madre lo inscribe en la Escuela de Artes de Baltimore en donde aprenderia clases de actuación y ballet. Nuevamente se mudo y no termino las clases esta vez se mudaba al Oeste de E.U. en Oakland, California (Marin City).

Fue entonces cuando su madre (Afeni) se vuelve adicta al Crack, debido a la pobreza y problemas que la agoviaban, para ese entonces Túpac tenia ya 16 años y su madre lo hechaba de la casa debido a la adicción de Afeni. Tú´pac se sumerge en el bajo mundo ganando dinero ilegalmente, revendiendo droga en las calles para poder sobrevivir.

Comenzo a hacer rap con su primer agrupación “Strictly Dope”, a los 17 años Túpac se mete al mundo del rap escribieno sus propias letras de canciones, en ese tiempo la gente le temia a los raperos de Nueva York por su mala fama de pandillerismo por lo cual pensaban que Túpac era igual y que seguramente pertenecia a alguna banda.

Cuando inicia su carrera no parecia muy prometedor su futuro como rapero, el comenzo como vocalista y bailarin del grupo “Digital Underground”, Túpac se unio a este despues de que la banda tuviera su epoca dorada con sus exitos.

En el año 1992, a la edad de 20 años, Túpac graba su album de debut como solista “2Pacalypse Now” (2pacalispsis Ahora), el cúal incluía su éxito Brenda’s Got A Baby (Brenda tuvo un bebe), con el cúal hace su presentación como una gran propuesta en el mundo del hip hop y lo lleva a ser su primer filme cinematográfico “Juice”(Jugo), con el papel estelar de Bishop.

Si quieren saber en que termina la historia de Túpac Mañana se las escribire y tratare de poner algunas fotos de Túpac.

Su carnal Jeswon. Recuerden este 13 de Septiembre se cumple un año mas de su muerte.

Dios no permitio que siguiera entre nosotros,
nos privo de su presencia,
pero el nos dejo su musica y poesia como legado,
para recordarlo siempre y que al oirlo,
viva en nuestros corazones.



[ Enlace | Dos es mejor que uno... supongo :/ ] del.icio.us del.icio.us Estrella este post ***** Música

Túpac Amaru Shakur Historia...

vie 09 de septiembre, 2005 - 20:39

Estado de ánimo: X
Seguridad de entrada: PUBLICO

Mañana pondre la historia de Túpac Amaru Shakur, como comenzo y el dia de su muerte.



[ Enlace | 7 comentarios ] del.icio.us del.icio.us Estrella este post ***** General

Desolado

sáb 11 de junio, 2005 - 16:26

Estado de ánimo: Triste
Seguridad de entrada: PUBLICO

Hoy desperte con tristeza
pensando en las cosas malas de mi vida,
en lo bueno y malo ke he hecho,
en lo ke pude haber logrado,
en las personas ke he lastimado
y en las ke no he podido ayudar.

Hoy he pensado en las cosas ke critico
y ke no he podido ayudar a cambiar
hoy recorde viejos amores ke se fueron
otros ke no llegaron y
amores ke no supe tener por miedo
por cobardia, amores
ke han dejado huella en mi vida.

Hoy pense en los amigos,
y senti nostalgia
al verme solo y sin alegrias,
sin una pareja a kien darle
todo el amor y el cariño ke hay en mi,
de recibir solo angustias y malas experiencias.

Hoy se acerca el final del dia
y he decidido tratar de vivir la vida,
de ser feliz y gozar los momentos
mas simples de mi alrededor.



[ Enlace | Tres comentarios ] del.icio.us del.icio.us Estrella este post ***** General

Carta de Amor.

sáb 04 de junio, 2005 - 19:44

Estado de ánimo: Melancólico
Seguridad de entrada: PUBLICO
foto de jeswon Amparo posando para la foto

Amparo no te das cuenta de ke te kiero, he cambiado muchas cosas de mi vida para ganarme tu cariño mas sin embargo solo he logrado alejarte, he visto como has crecido en estos años y cada dia me enamoro mas de ti, sufro en silencio por no tenerte a mi lado pero me reconforta saber ke eres feliz aunke yo no sea parte de esa felicidad.

Solo espero ke alguna vez puedas darme la oportunidad de ganarme tu amor y cariño, no kiero un amor de rato pero tampoco presionarte a un amor total, solo dejame hacerte feliz mas de lo ke eres ya.



[ Enlace | Sin comentarios :'( ] del.icio.us del.icio.us Estrella este post ***** Amor - desamor

Sangre de indio, Fotos Coatzacoalcos.

jue 02 de junio, 2005 - 12:06

Estado de ánimo: Emocionado
Seguridad de entrada: PUBLICO

Ayer nuevamente me senti orgulloso de llevar en mis venas sangre de indio y ser Mexicano, de ser nopalero de corazon y costeño de nacimiento.

Con motivo del evento Internacional de Encuentro del Mar 2005 llevado a cabo en el Puerto de Coatzacoalcos y el festejo del dia de la Marina, se realizo un montaje de un ataque maritimo a un barco en el cual se descargaron cantidades de municiones en contra de este y finalizo con el lanzamiento por primera vez en la historia de la Armada de México de 2 misiles para terminar de undir el barco. Este acto se llevo a cabo en presencia del wey del Presidente Fox y del Gobernador de Veracruz Fidel.

En conjunto de estos actos se realizaran a lo largo de la semana actos culturales y foros de discusion de temas realizados en torno de la cuestion maritima y su contaminacion.

Poco a poco la Ciudad de Coatzacoalcos, Veracruz van en pro del progreso tratando de traer turismo e inversiones para el sustento economico de la ciudad.

Luego pondre unas fotos para que vean como estuvo el rollo y conoscan mi ciudad por el momento ahi les van unas cuantas.
















[ Enlace | 19 comentarios ] del.icio.us del.icio.us Estrella este post ***** General

XBOX 360

sáb 14 de mayo, 2005 - 20:53

Estado de ánimo: X
Seguridad de entrada: PUBLICO

Me acabo de enterar ke en noviembre sale la XBOX 360 de Microsoft ke trae consigo 3 CPU’s de 3GHZ, 512 MB de RAM, Disco Duro de 20GB Extraible y procesador Nvidia.

Esta XBOX trae un nuevo diseño chingon pero ya se acerca al estilo de las PC’s con un gabinete minitorre.

La neta esta chingon espero el dia ke este a la venta aki en Coatza para salir corriendo a comprarla.



[ Enlace | 5 comentarios ] del.icio.us del.icio.us Estrella este post ***** General

Que hago? Help Me

sáb 23 de abril, 2005 - 19:50

Estado de ánimo: Alegre
Seguridad de entrada: PUBLICO
Música actual: Kensuke Shina

Bueno si bien algunos de ustedes ya saben mi historia con la hija de mi cuñado (mi sobrinastra, jejeje), mañana viene voy a aprovechar para invitarla a salir y hablar bien con ella para saber que p2 con nosotros si vamos o no a tener algo, pero la neta no se ni como empezar a decirle, no se si pueda aguantarme las ganas de poder agarrarla a besos, mi cuñado ya sabe que peps con su hija y yo pero aun asi me da un poquitillo de incertidumbre jejejej.

La neta no se si logre hacer algo mañana con ella solo espero que pueda resultar algo bueno y que pueda encontrar las palabras para convencerla de que no tiene nada de malo que seamos pareja, pero la neta si ustedes pueden orientarme se los agradeceria muchisimo, jejejeje.



[ Enlace | 5 comentarios ] del.icio.us del.icio.us Estrella este post ***** Amor - desamor

Mi novia la hija d mi cuñado?.

sáb 16 de abril, 2005 - 21:18

Estado de ánimo: Confundido
Seguridad de entrada: PUBLICO

La neta no se como vean lo que les voy a contar, solo espero puedan ayudarme con este pequeño enredo mental que traigo.

Lo que pasa es lo siguiente. Mi hermana se caso hace diez años con un ñor que le lleva muchos años el cual era un cabron mujeriego y tiene un chingo de hijos se conpuso despues de casarse con mi carnala, el problema es el siguiente una de sus hijas la conoci cuando estaba morrita (ella tiene 17 y yo 21 años, le llevo 4 años,) la deje de ver hace seis años y ahora que la he visto de nuevo me dejo impactado lo chula que se puso la canija tiene un cuerpo que la verdad dan ganas de agarrar a mordidas, y tiene una carita angelical y muy finita aunque tiene un caracter como el mio y por eso me gusta mas.

El problema es que quiero que sea mi novia pero no se si este bien realmente no tenemos parentesco de sangre pero que hago le digo o no le digo, y lo cosa esta en que creo que ella tambien quiere que seamos algo, pero me ha dicho que le da pena por su papá y mi carnala.

Ya hasta estoy pensando en consultar a mi cura de cabecera para preguntarle que peps…



[ Enlace | 16 comentarios ] del.icio.us del.icio.us Estrella este post ***** Amor - desamor

NoteBook, yo quiero una

sáb 09 de abril, 2005 - 17:56

Estado de ánimo: Triste
Seguridad de entrada: PUBLICO
foto de jeswon NoteBook, yo quiero una

Vaya tecnologia como avanza cada dia es mas compleja. O no?.



[ Enlace | Sin comentarios :'( ] del.icio.us del.icio.us Estrella este post ***** General

Manual Java 3ra. parte

mié 06 de abril, 2005 - 16:50

Estado de ánimo: X
Seguridad de entrada: PUBLICO

PanelIzq.add(PanelDNI);
PanelIzq.add(PanelNombre);
PanelIzq.add(PanelRFC);
PanelIzq.add(PanelDIR);
PanelIzq.add(PanelTEL);
PanelIzq.add(PanelCiudad);
PanelIzq.add(PanelCP);

PPanelIzq.add(PPanelDNI);
PPanelIzq.add(PPanelNombre);
PPanelIzq.add(PPanelRFC);
PPanelIzq.add(PPanelDIR);
PPanelIzq.add(PPanelTEL);
PPanelIzq.add(PPanelCiudad);
PPanelIzq.add(PPanelCP);

PRPanelIzq.add(PRPanelDNI);
PRPanelIzq.add(PRPanelNombre);
PRPanelIzq.add(PRPanelDes);
PRPanelIzq.add(PRPanelUnidad);
PRPanelIzq.add(PRPanelFing);
PRPanelIzq.add(PRPanelCmin);
PRPanelIzq.add(PRPanelCmax);
PRPanelIzq.add(PRPanelExistencia);
PRPanelIzq.add(PRPanelPprod);
PRPanelIzq.add(PRPanelPvta);

VtaPanelIzq.add(VtaPanelDNI);
VtaPanelIzq.add(VtaPanelNombre);

VtaPanelIzq.add(VtaPanelDes);
VtaPanelIzq.add(VtaPanelPrecio);
VtaPanelIzq.add(VtaPanelCant);
VtaPanelIzq.add(VtaPanelSub);
VtaPanelIzq.add(VtaPanelTotal);

PanelReloj.add(etiqReloj);
PanelReloj2.add(txt1);

PanelHora.add(PanelReloj);
PanelHora.add(PanelReloj2);
PanelHora.add(SalirSistema);

MiPanel.add(PanelHora);
MiPanel.add(Panel1);
MiPanel.add(Panel2);
MiPanel.add(Panel3);
MiPanel.add(Panel4);
MiPanel.add(Panel5);

PanelIzq.add(PanelAccion);
PanelIzq.add(PanelControles);

PPanelIzq.add(PPanelAccion);
PPanelIzq.add(PPanelControles);

PRPanelIzq.add(PRPanelAccion);
PRPanelIzq.add(PRPanelControles);

VtaPanelIzq.add(VtaPanelAccion);
VtaPanelIzq.add(VtaPanelControles);

MiPanel2.add(PanelIzq);
MiPanel2.add(PanelTabla);

MiPanel3.add(PPanelIzq);
MiPanel3.add(PPanelTabla);

MiPanel4.add(PRPanelIzq);
MiPanel4.add(PRPanelTabla);

MiPanel5.add(VtaPanelIzq);
MiPanel5.add(PanelVentas);

PanelDNI.add(EtiquetaNum);PanelDNI.add(CampoNum_Cli);
PanelNombre.add(EtiquetaNombre);PanelNombre.add(CampoNom_Cli);
PanelRFC.add(EtiquetaRFC);PanelRFC.add(CampoRFC_Cli);
PanelDIR.add(EtiquetaDIR);PanelDIR.add(CampoDir_Cli);
PanelTEL.add(EtiquetaTEL);PanelTEL.add(CampoTel_Cli); PanelCiudad.add(EtiquetaCiudad);PanelCiudad.add(CampoCd_Cli); PanelCP.add(EtiquetaCP);PanelCP.add(CampoCP_Cli);

PPanelDNI.add(EtiquetaPNum);PPanelDNI.add(CampoNum_Prov); PPanelNombre.add(EtiquetaPNombre);PPanelNombre.add(CampoNom_Prov); PPanelRFC.add(EtiquetaPRFC);PPanelRFC.add(CampoRFC_Prov); PPanelDIR.add(EtiquetaPDIR);PPanelDIR.add(CampoDir_Prov); PPanelTEL.add(EtiquetaPTEL);PPanelTEL.add(CampoTel_Prov); PPanelCiudad.add(EtiquetaPCiudad);PPanelCiudad.add(CampoCd_Prov); PPanelCP.add(EtiquetaPCP);PPanelCP.add(CampoCP_Prov);

PRPanelDNI.add(EtiquetaNum_Prod);PRPanelDNI.add(CampoNum_Prod); PRPanelNombre.add(EtiquetaNom_Prod);PRPanelNombre.add(CampoNom_Prod); PRPanelDes.add(EtiquetaDescripcion);PRPanelDes.add(CampoDescripcion); PRPanelUnidad.add(EtiquetaUnidad);PRPanelUnidad.add(CampoUnidad); PRPanelFing.add(EtiquetaFecha_ingreso);PRPanelFing.add(CampoFecha_ingreso); PRPanelCmin.add(EtiquetaCan_min);PRPanelCmin.add(CampoCan_min);

PRPanelCmax.add(EtiquetaCan_max);PRPanelCmax.add(CampoCan_max); PRPanelExistencia.add(EtiquetaExistencia);PRPanelExistencia.add(CampoExistencia); PRPanelPprod.add(EtiquetaPrecio_Prod);PRPanelPprod.add(CampoPrecio_Prod); PRPanelPvta.add(EtiquetaPrecio_Vta);PRPanelPvta.add(CampoPrecio_Vta);

VtaPanelDNI.add(EtiquetaNum_ProdVta); VtaPanelDNI.add(NumeroProducto);
VtaPanelNombre.add(EtiquetaNom_ProdVta); VtaPanelNombre.add(NombreProducto);
VtaPanelDes.add(EtiquetaDescripcion); VtaPanelDes.add(Descrip);
VtaPanelPrecio.add(EtiquetaPrecio); VtaPanelPrecio.add(Precio);
VtaPanelCant.add(EtiquetaCant); VtaPanelCant.add(Cant);
VtaPanelSub.add(EtiquetaSub); VtaPanelSub.add(Subtotal);
VtaPanelTotal.add(EtiquetaTotal); VtaPanelTotal.add(Total);

PanelAccion.add(BotonConsultar); PanelAccion.add(BotonModificar); PanelAccion.add(BotonInsertar); PanelAccion.add(BotonBorrar); PanelAccion.add(BotonListar); PanelControles.add(BotonPrimero); PanelControles.add(BotonMenosCinco); PanelControles.add(BotonAnterior); PanelControles.add(BotonSiguiente); PanelControles.add(BotonMasCinco); PanelControles.add(BotonUltimo);

PPanelAccion.add(BotonPConsultar); PPanelAccion.add(BotonPModificar); PPanelAccion.add(BotonPInsertar); PPanelAccion.add(BotonPBorrar);

PPanelAccion.add(BotonPListar); PPanelControles.add(BotonPPrimero); PPanelControles.add(BotonPMenosCinco); PPanelControles.add(BotonPAnterior); PPanelControles.add(BotonPSiguiente); PPanelControles.add(BotonPMasCinco); PPanelControles.add(BotonPUltimo);

PRPanelAccion.add(BotonPRConsultar); PRPanelAccion.add(BotonPRModificar); PRPanelAccion.add(BotonPRInsertar); PRPanelAccion.add(BotonPRBorrar); PRPanelAccion.add(BotonPRListar); PRPanelControles.add(BotonPRPrimero); PRPanelControles.add(BotonPRMenosCinco); PRPanelControles.add(BotonPRAnterior); PRPanelControles.add(BotonPRSiguiente); PRPanelControles.add(BotonPRMasCinco); PRPanelControles.add(BotonPRUltimo);

VtaPanelAccion.add(BotonBuscar); VtaPanelControles.add(BotonAgregar);

SalirSistema.addActionListener(new Salir()); BotonConsultar.addActionListener(new ConsultarDatos()); BotonModificar.addActionListener(new ModificarDatos()); BotonInsertar.addActionListener(new InsertarDatos()); BotonBorrar.addActionListener(new BorrarDatos()); BotonListar.addActionListener(new ListarDatos());

BotonPrimero.addActionListener(new Controles()); BotonMenosCinco.addActionListener(new Controles()); BotonAnterior.addActionListener(new Controles()); BotonSiguiente.addActionListener(new Controles()); BotonMasCinco.addActionListener(new Controles()); BotonUltimo.addActionListener(new Controles());

BotonPConsultar.addActionListener(new PConsultarDatos()); BotonPModificar.addActionListener(new PModificarDatos()); BotonPInsertar.addActionListener(new PInsertarDatos()); BotonPBorrar.addActionListener(new PBorrarDatos()); BotonPListar.addActionListener(new PListarDatos());

BotonPPrimero.addActionListener(new PControles()); BotonPMenosCinco.addActionListener(new PControles()); BotonPAnterior.addActionListener(new PControles()); BotonPSiguiente.addActionListener(new PControles()); BotonPMasCinco.addActionListener(new PControles()); BotonPUltimo.addActionListener(new PControles());

BotonPRConsultar.addActionListener(new PRConsultarDatos());

BotonPRModificar.addActionListener(new PRModificarDatos()); BotonPRInsertar.addActionListener(new PRInsertarDatos()); BotonPRBorrar.addActionListener(new PRBorrarDatos()); BotonPRListar.addActionListener(new PRListarDatos());

BotonPRPrimero.addActionListener(new PRControles()); BotonPRMenosCinco.addActionListener(new PRControles()); BotonPRAnterior.addActionListener(new PRControles()); BotonPRSiguiente.addActionListener(new PRControles()); BotonPRMasCinco.addActionListener(new PRControles()); BotonPRUltimo.addActionListener(new PRControles());

BotonVenta.addActionListener(new Ventas()); BotonVarios.addActionListener(new VariosPC());

BotonBuscar.addActionListener(new Buscar()); //BotonAgregar.addActionListener(new Agregar()); Cant.addActionListener(new Operar());

NombreProducto.setEnabled(false); Descrip.setEnabled(false); Precio.setEnabled(false); Subtotal.setEnabled(false); Total.setEnabled(false);

int x,y; formatter = new SimpleDateFormat (“hh:mm:ss”,Locale.getDefault()); currentDate = new Date(); lastdate = formatter.format(currentDate); lastdate2 = formatter.format(currentDate); lastdate3 = formatter.format(currentDate);

timer = new Thread(this); timer.start();

Formulario = new JFrame(“Base de Datos ADSIJEL (CLIENTES): “); Formulario.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);}}); Formulario.setBackground(Color.lightGray); Formulario.getContentPane().add(MiPanel); Formulario.setBounds(5, 0, 400, 330);

Formulario2 = new JFrame(“Base de Datos ADSIJEL (CLIENTES): “); Formulario2.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Formulario.setVisible(true);}}); Formulario2.setBackground(Color.lightGray); Formulario2.getContentPane().add(MiPanel2); Formulario2.setBounds(50, 250, 490, 230);

Formulario3 = new JFrame(“Base de Datos ADSIJEL (CLIENTES): “); Formulario3.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Formulario.setVisible(true); }}); Formulario3.setBackground(Color.lightGray); Formulario3.getContentPane().add(MiPanel3); Formulario3.setBounds(50, 250, 490, 230);

Formulario4 = new JFrame(“Base de Datos ADSIJEL (PRODUCTOS): “); Formulario4.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {

Formulario.setVisible(true); }}); Formulario4.setBackground(Color.lightGray); Formulario4.getContentPane().add(MiPanel4); Formulario4.setBounds(50, 250, 490, 230);

Formulario5 = new JFrame(“Base de Datos ADSIJEL ==> UNION: (CLIENTES / PROVEEDORES): “); Formulario5.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Formulario.setVisible(true); }}); Formulario5.setBackground(Color.lightGray); Formulario5.getContentPane().add(PanelTablaVarios);

Formulario6 = new JFrame(“Base de Datos ADSIJEL ==> UNION: (CLIENTES / PROVEEDORES): “); Formulario6.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Formulario.setVisible(true); }}); Formulario6.setBackground(Color.lightGray); Formulario6.getContentPane().add(MiPanel5);

FormPrincipal = new JFrame(“PAPELERIA JELANSA ‘’ A D S I J E L ‘’”); FormPrincipal.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);}}); FormPrincipal.setBackground(Color.lightGray); FormPrincipal.getContentPane().add(MiPanelPrincipal); Desbloquear(); if(band=true) { Formulario.pack(); Formulario.setVisible(true); } } private class ConsultarDatos implements ActionListener{ public void actionPerformed (ActionEvent Evento){ ObConsulta InstanciaConsulta=new ObConsulta (CampoNum_Cli.getText()); PosicionBuscada=InstanciaConsulta.PosicionEncontrada(); if(PosicionBuscada!=0){ ObRegistro InstanciaFila=InstanciaConsulta.DameDatos(); CampoNum_Cli.setText(InstanciaFila.DameNum()); CampoNom_Cli.setText(InstanciaFila.DameNombre()); CampoRFC_Cli.setText(InstanciaFila.DameRFC()); CampoDir_Cli.setText(InstanciaFila.DameDIR()); CampoTel_Cli.setText(InstanciaFila.DameTEL()); CampoCd_Cli.setText(InstanciaFila.DameCiudad()); CampoCP_Cli.setText(InstanciaFila.DameCP()); }else{ CampoNom_Cli.setText(”——-”); CampoRFC_Cli.setText(”——-”); CampoDir_Cli.setText(”——-”); CampoTel_Cli.setText(”——-”); CampoCd_Cli.setText(”——-”); CampoCP_Cli.setText(”——-”); } } }

private class InsertarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ try{ ObRegistro InstanciaFila=new ObRegistro (CampoNum_Cli.getText(),CampoNom_Cli.getText(),CampoRFC_Cli.getText(),CampoDir_Cli.getText(),CampoTel_Cli.getText(),CampoCd_Cli.getText(),CampoCP_Cli.getText()); ObInsercion InstanciaInsercion=new ObInsercion(InstanciaFila); CampoNum_Cli.setText(”“); CampoNom_Cli.setText(”“); CampoRFC_Cli.setText(”“); CampoDir_Cli.setText(”“); CampoTel_Cli.setText(”“); CampoCd_Cli.setText(”“); CampoCP_Cli.setText(”“);; PosicionBuscada=1; } catch(Exception e){ System.out.println(“Llena todos los registros…!”); } } } private class ModificarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ ObConsulta InstanciaConsulta=new ObConsulta(CampoNum_Cli.getText()); PosicionBuscada=InstanciaConsulta.PosicionEncontrada(); if(PosicionBuscada!=0){ ObRegistro InstanciaFila=new ObRegistro (CampoNum_Cli.getText(),CampoNom_Cli.getText(),CampoRFC_Cli.getText(),CampoDir_Cli.getText(),CampoTel_Cli.getText(),CampoCd_Cli.getText(),CampoCP_Cli.getText());

ObModificacion InstanciaModificacion=new ObModificacion(PosicionBuscada,InstanciaFila); CampoNum_Cli.setText(”“); CampoNom_Cli.setText(”“); CampoRFC_Cli.setText(”“); CampoDir_Cli.setText(”“);

CampoTel_Cli.setText(”“); CampoCd_Cli.setText(”“); CampoCP_Cli.setText(”“); }else{ CampoNom_Cli.setText(”——-”); CampoRFC_Cli.setText(”——-”); CampoDir_Cli.setText(”——-”); CampoTel_Cli.setText(”——-”); CampoCd_Cli.setText(”——-”); CampoCP_Cli.setText(”——-”); } } } private class BorrarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ ObConsulta InstanciaConsulta=new ObConsulta(CampoNum_Cli.getText()); PosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PosicionBuscada!=0){ ObBorrado InstanciaBorrado=new ObBorrado(PosicionBuscada);

CampoNum_Cli.setText(”“); CampoNom_Cli.setText(”“); CampoRFC_Cli.setText(”“); CampoDir_Cli.setText(”“); CampoTel_Cli.setText(”“); CampoCd_Cli.setText(”“); CampoCP_Cli.setText(”“); }else{ CampoNom_Cli.setText(”——-”); CampoRFC_Cli.setText(”——-”); CampoDir_Cli.setText(”——-”); CampoTel_Cli.setText(”——-”); CampoCd_Cli.setText(”——-”); CampoCP_Cli.setText(”——-”); } } } private class ListarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ connect(); fetch(); } } private class Controles implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Button Pulsado=(Button) Evento.getSource(); String Identificador=Pulsado.getName(); ObPosicionamiento InstanciaPosicionamiento =new ObPosicionamiento(Identificador, PosicionBuscada); ObRegistro InstanciaFila= InstanciaPosicionamiento.DameDatos(); CampoNum_Cli.setText(InstanciaFila.DameNum()); CampoNom_Cli.setText(InstanciaFila.DameNombre()); CampoRFC_Cli.setText(InstanciaFila.DameRFC());

CampoDir_Cli.setText(InstanciaFila.DameDIR()); CampoTel_Cli.setText(InstanciaFila.DameTEL()); CampoCd_Cli.setText(InstanciaFila.DameCiudad()); CampoCP_Cli.setText(InstanciaFila.DameCP()); PosicionBuscada=InstanciaPosicionamiento.Posicion(); } }

private class VariosPC implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Formulario5.pack(); Formulario5.setVisible(true); Formulario5.setBounds(50, 250, 470, 450); connectVarios(); fetchVarios(); } }

private class PConsultarDatos implements ActionListener{ public void actionPerformed (ActionEvent Evento){ PObConsulta InstanciaConsulta=new PObConsulta (CampoNum_Prov.getText()); PPosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PPosicionBuscada!=0){ PObRegistro InstanciaFila=InstanciaConsulta.DameDatos();

CampoNum_Prov.setText(InstanciaFila.DameNum()); CampoNom_Prov.setText(InstanciaFila.DameNombre()); CampoRFC_Prov.setText(InstanciaFila.DameRFC()); CampoDir_Prov.setText(InstanciaFila.DameDIR()); CampoTel_Prov.setText(InstanciaFila.DameTEL()); CampoCd_Prov.setText(InstanciaFila.DameCiudad()); CampoCP_Prov.setText(InstanciaFila.DameCP()); }else{ CampoNom_Prov.setText(”——-”); CampoRFC_Prov.setText(”——-”); CampoDir_Prov.setText(”——-”); CampoTel_Prov.setText(”——-”); CampoCd_Prov.setText(”——-”); CampoCP_Prov.setText(”——-”); } } } private class PInsertarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){
try{ PObRegistro InstanciaFila=new PObRegistro (CampoNum_Prov.getText(),CampoNom_Prov.getText(),CampoRFC_Prov.getText(),CampoDir_Prov.getText(),CampoTel_Prov.getText(),CampoCd_Prov.getText(),CampoCP_Prov.getText()); PObInsercion InstanciaInsercion=new PObInsercion(InstanciaFila); CampoNum_Prov.setText(”“); CampoNom_Prov.setText(”“); CampoRFC_Prov.setText(”“); CampoDir_Prov.setText(”“); CampoTel_Prov.setText(”“); CampoCd_Prov.setText(”“); CampoCP_Prov.setText(”“);; PPosicionBuscada=1; } catch(Exception e){ System.out.println(“Llena todos los registros…!”); } } } private class PModificarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ PObConsulta InstanciaConsulta=new PObConsulta(CampoNum_Prov.getText()); PPosicionBuscada=InstanciaConsulta.PosicionEncontrada(); if(PPosicionBuscada!=0){ PObRegistro InstanciaFila=new PObRegistro (CampoNum_Prov.getText(),CampoNom_Prov.getText(),CampoRFC_Prov.getText(),CampoDir_Prov.getText(),CampoTel_Prov.getText(),CampoCd_Prov.getText(),CampoCP_Prov.getText()); PObModificacion InstanciaModificacion=new PObModificacion(PPosicionBuscada,InstanciaFila); CampoNum_Prov.setText(”“); CampoNom_Prov.setText(”“); CampoRFC_Prov.setText(”“); CampoDir_Prov.setText(”“); CampoTel_Prov.setText(”“); CampoCd_Prov.setText(”“); CampoCP_Prov.setText(”“); }else{ CampoNom_Cli.setText(”——-”); CampoRFC_Cli.setText(”——-”); CampoDir_Cli.setText(”——-”); CampoTel_Cli.setText(”——-”); CampoCd_Cli.setText(”——-”); CampoCP_Cli.setText(”——-”); } } } private class PBorrarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ PObConsulta InstanciaConsulta=new PObConsulta(CampoNum_Prov.getText()); PPosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PPosicionBuscada!=0){ PObBorrado InstanciaBorrado=new PObBorrado(PPosicionBuscada); CampoNum_Prov.setText(”“); CampoNom_Prov.setText(”“); CampoRFC_Prov.setText(”“); CampoDir_Prov.setText(”“); CampoTel_Prov.setText(”“); CampoCd_Prov.setText(”“);

CampoCP_Prov.setText(”“); }else{ CampoNom_Prov.setText(”——-”); CampoRFC_Prov.setText(”——-”); CampoDir_Prov.setText(”——-”); CampoTel_Prov.setText(”——-”); CampoCd_Prov.setText(”——-”); CampoCP_Prov.setText(”——-”); }

} } private class PListarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Pconnect(); Pfetch(); } } private class PControles implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Button Pulsado=(Button) Evento.getSource(); String Identificador=Pulsado.getName(); PObPosicionamiento InstanciaPosicionamiento =new PObPosicionamiento(Identificador, PPosicionBuscada); PObRegistro InstanciaFila= InstanciaPosicionamiento.DameDatos(); CampoNum_Cli.setText(InstanciaFila.DameNum()); CampoNom_Cli.setText(InstanciaFila.DameNombre()); CampoRFC_Cli.setText(InstanciaFila.DameRFC()); CampoDir_Cli.setText(InstanciaFila.DameDIR()); CampoTel_Cli.setText(InstanciaFila.DameTEL()); CampoCd_Cli.setText(InstanciaFila.DameCiudad()); CampoCP_Cli.setText(InstanciaFila.DameCP()); PPosicionBuscada=InstanciaPosicionamiento.Posicion(); } }

private class PRConsultarDatos implements ActionListener{ public void actionPerformed (ActionEvent Evento){ PRObConsulta InstanciaConsulta=new PRObConsulta (CampoNum_Prod.getText()); PRPosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PRPosicionBuscada!=0){ PRObRegistro InstanciaFila=InstanciaConsulta.DameDatos(); CampoNum_Prod.setText(InstanciaFila.DameNum()); CampoNom_Prod.setText(InstanciaFila.DameNombre()); CampoDescripcion.setText(InstanciaFila.DameDesc()); CampoUnidad.setText(InstanciaFila.DameUnidad()); CampoFecha_ingreso.setText(InstanciaFila.DameFing()); CampoCan_min.setText(InstanciaFila.DameCmin()); CampoCan_max.setText(InstanciaFila.DameCmax());

CampoExistencia.setText(InstanciaFila.DameExistencia()); CampoPrecio_Prod.setText(InstanciaFila.DamePprod()); CampoPrecio_Vta.setText(InstanciaFila.DamePvta()); }else{ CampoNom_Prod.setText(”——-”); CampoDescripcion.setText(”——-”); CampoUnidad.setText(”——-”);

CampoFecha_ingreso.setText(”——-”); CampoCan_min.setText(”——-”); CampoCan_max.setText(”——-”); CampoExistencia.setText(”——-”); CampoPrecio_Prod.setText(”——-”); CampoPrecio_Vta.setText(”——-”); } } } private class PRInsertarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){
try{ PRObRegistro InstanciaFila=new PRObRegistro (CampoNum_Prod.getText(),CampoNom_Prod.getText(),CampoDescripcion.getText(), CampoUnidad.getText(),CampoFecha_ingreso.getText(),CampoCan_min.getText(),CampoCan_max.getText(), CampoExistencia.getText(),CampoPrecio_Prod.getText(),CampoPrecio_Vta.getText()); PRObInsercion InstanciaInsercion=new PRObInsercion(InstanciaFila); CampoNom_Prod.setText(”“); CampoDescripcion.setText(”“); CampoUnidad.setText(”“); CampoFecha_ingreso.setText(”“); CampoCan_min.setText(”“); CampoCan_max.setText(”“); CampoExistencia.setText(”“); CampoPrecio_Prod.setText(”“); CampoPrecio_Vta.setText(”“); PRPosicionBuscada=1; }

catch(Exception e){ System.out.println(“Llena todos los registros…!”); } } } private class PRModificarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ PRObConsulta InstanciaConsulta=new PRObConsulta(CampoNum_Prod.getText()); PRPosicionBuscada=InstanciaConsulta.PosicionEncontrada(); if(PRPosicionBuscada!=0){ PRObRegistro InstanciaFila=new PRObRegistro (CampoNum_Prod.getText(),CampoNom_Prod.getText(),CampoDescripcion.getText(), CampoUnidad.getText(),CampoFecha_ingreso.getText(),CampoCan_min.getText(),CampoCan_max.getText(), CampoExistencia.getText(),CampoPrecio_Prod.getText(),CampoPrecio_Vta.getText());

PRObModificacion InstanciaModificacion=new PRObModificacion(PRPosicionBuscada,InstanciaFila);

CampoNum_Prod.setText(”“); CampoNom_Prod.setText(”“); CampoDescripcion.setText(”“); CampoUnidad.setText(”“); CampoFecha_ingreso.setText(”“); CampoCan_min.setText(”“); CampoCan_max.setText(”“); CampoExistencia.setText(”“);

CampoPrecio_Prod.setText(”“); CampoPrecio_Vta.setText(”“); }else{ CampoNom_Prod.setText(”———”); CampoDescripcion.setText(”———”); CampoUnidad.setText(”———”); CampoFecha_ingreso.setText(”———”); CampoCan_min.setText(”———”); CampoCan_max.setText(”———”); CampoExistencia.setText(”———”); CampoPrecio_Prod.setText(”———”); CampoPrecio_Vta.setText(”———”); } } }

private class PRBorrarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ PRObConsulta InstanciaConsulta=new PRObConsulta(CampoNum_Prod.getText()); PRPosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PRPosicionBuscada!=0){ PRObBorrado InstanciaBorrado=new PRObBorrado(PRPosicionBuscada); CampoNum_Prod.setText(”“); CampoNom_Prod.setText(”“); CampoDescripcion.setText(”“); CampoUnidad.setText(”“); CampoFecha_ingreso.setText(”“); CampoCan_min.setText(”“); CampoCan_max.setText(”“); CampoExistencia.setText(”“); CampoPrecio_Prod.setText(”“); CampoPrecio_Vta.setText(”“); }else{ CampoNom_Prod.setText(”———”); CampoDescripcion.setText(”———”); CampoUnidad.setText(”———”); CampoFecha_ingreso.setText(”———”); CampoCan_min.setText(”———”); CampoCan_max.setText(”———”); CampoExistencia.setText(”———”); CampoPrecio_Prod.setText(”———”); CampoPrecio_Vta.setText(”———”);

} } } private class PRListarDatos implements ActionListener{ public void actionPerformed(ActionEvent Evento){ PRconnect(); PRfetch(); } }

private class PRControles implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Button Pulsado=(Button) Evento.getSource(); String Identificador=Pulsado.getName(); PRObPosicionamiento InstanciaPosicionamiento =new PRObPosicionamiento(Identificador, PRPosicionBuscada); PRObRegistro InstanciaFila= InstanciaPosicionamiento.DameDatos();

CampoNum_Prod.setText(InstanciaFila.DameNum()); CampoNom_Prod.setText(InstanciaFila.DameNombre()); CampoDescripcion.setText(InstanciaFila.DameDesc()); CampoUnidad.setText(InstanciaFila.DameUnidad()); CampoFecha_ingreso.setText(InstanciaFila.DameFing()); CampoCan_min.setText(InstanciaFila.DameCmin()); CampoCan_max.setText(InstanciaFila.DameCmax()); CampoExistencia.setText(InstanciaFila.DameExistencia()); CampoPrecio_Prod.setText(InstanciaFila.DamePprod()); CampoPrecio_Vta.setText(InstanciaFila.DamePvta()); PRPosicionBuscada=InstanciaPosicionamiento.Posicion(); } }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private class Buscar implements ActionListener{ public void actionPerformed (ActionEvent Evento){ PRObConsulta InstanciaConsulta=new PRObConsulta (NumeroProducto.getText()); PRPosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PRPosicionBuscada!=0){ PRObRegistro InstanciaFila=InstanciaConsulta.DameDatos(); NumeroProducto.setText(InstanciaFila.DameNum());

NombreProducto.setText(InstanciaFila.DameNombre()); Descrip.setText(InstanciaFila.DameDesc()); Precio.setText(InstanciaFila.DamePvta());

}else{ NumeroProducto.setText(”——-”); NombreProducto.setText(”——-”);

Descrip.setText(”——-”); Cant.setText(”——-”); Precio.setText(”——-”); Subtotal.setText(”——-”); Total.setText(”——-”);

} } }

public void connect() { BaseDeDato = new ListarJDBC(“jdbc:odbc:ADSIJEL”,“sun.jdbc.odbc.JdbcOdbcDriver”,“Chano”,“veracruz”); Tabla.setModel(BaseDeDato); }

public void fetch() { BaseDeDato.executeQuery(“SELECT * FROM CLIENTES”); }

Thread s, concurrent execution, and synchronization 131

public void Pconnect() { BaseDeDato = new ListarJDBC(“jdbc:odbc:ADSIJEL”,“sun.jdbc.odbc.JdbcOdbcDriver”,“Chano”,“veracruz”); Tabla.setModel(BaseDeDato); }
public void Pfetch() { BaseDeDato.executeQuery(“SELECT * FROM PROVEEDOR”); }

public void PRconnect() { BaseDeDato = new ListarJDBC(“jdbc:odbc:ADSIJEL”,“sun.jdbc.odbc.JdbcOdbcDriver”,“Chano”,“veracruz”); Tabla.setModel(BaseDeDato); }
public void PRfetch() { BaseDeDato.executeQuery(“SELECT * FROM PRODUCTOS”); }

public void connectVarios() { BaseDeDato = new ListarJDBC(“jdbc:odbc:ADSIJEL”,“sun.jdbc.odbc.JdbcOdbcDriver”,“Chano”,“veracruz”); Tabla.setModel(BaseDeDato); }
public void fetchVarios() { BaseDeDato.executeQuery(“SELECT CLIENTES.,‘Cliente’ AS [Relación] FROM CLIENTES UNION SELECT PROVEEDOR., ‘Proveedor’ FROM PROVEEDOR”); }

public JScrollPane crearTabla() { Tabla = new TipoTabla(); JTable table = new JTable(Tabla); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Tabla.addMouseListenerToHeaderInTable(table); JScrollPane scrollpane = new JScrollPane(table); return scrollpane; }

public JScrollPane PcrearTabla() { PTabla = new TipoTabla(); JTable table = new JTable(Tabla); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Tabla.addMouseListenerToHeaderInTable(table); JScrollPane scrollpane = new JScrollPane(table); return scrollpane; }

public JScrollPane PanelTablaVarios() { PTabla = new TipoTabla(); JTable table = new JTable(Tabla); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Tabla.addMouseListenerToHeaderInTable(table); JScrollPane scrollpane = new JScrollPane(table); return scrollpane; }

public JScrollPane PRcrearTabla() { PTabla = new TipoTabla(); JTable table = new JTable(Tabla); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Tabla.addMouseListenerToHeaderInTable(table); JScrollPane scrollpane = new JScrollPane(table); return scrollpane; }

public static void main (String [] args){ new Principal(); }

private class Cliente implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Formulario2.pack(); Formulario2.setVisible(true); } }

private class Operar implements ActionListener{ public void actionPerformed(ActionEvent Evento){

Subtotal.setText(”“+Integer.parseInt(Cant.getText())*Integer.parseInt(Precio.getText())); Total.setText(”“+Integer.parseInt(Subtotal.getText())*1.15); } }

private class Proveedor implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Formulario3.pack(); Formulario3.setVisible(true); } }

private class Producto implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Formulario4.pack(); Formulario4.setVisible(true); } }

private class Salir implements ActionListener{ public void actionPerformed(ActionEvent Evento){ if(JOptionPane.showOptionDialog(AgregarTabla, preg, “Cerrando Sistema ADSIJEL”, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, BotonDialogo, BotonDialogo0)==0){ System.exit(0);} } }

private class Ventas implements ActionListener{ public void actionPerformed(ActionEvent Evento){ Formulario6.pack(); Formulario6.setVisible(true); } }

public void run() { Thread me = Thread.currentThread(); while (timer == me) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { }

while (Cronometro == me) { try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } } Regresar(); } } public void Regresar() {

int s = 0, m = 10, h = 10; String today;

currentDate = new Date();

formatter.applyPattern(“s”); try { s = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { s = 0; } formatter.applyPattern(“m”); try { m = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { m = 10; } formatter.applyPattern(“h”); try { h = Integer.parseInt(formatter.format(currentDate)); } catch (NumberFormatException n) { h = 10; } formatter.applyPattern(“HH:mm:ss”); today = formatter.format(currentDate); txt1.setText(”“+lastdate); lastdate = today; lastdate2 = today; lastdate3 = today; currentDate = null; }

public void Desbloquear() { if(JOptionPane.showOptionDialog(AgregarTabla, DatosPanel, “Datos de Usuario”, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, BotonDialogoBegin, BotonDialogoBegin0)==0){ Conexion InstanciaConsulta=new Conexion (Usuario.getText(),Contraseña.getText()); PosicionBuscada=InstanciaConsulta.PosicionEncontrada();

if(PosicionBuscada!=0){ band=true; }

else{ JOptionPane.showMessageDialog(null ,“Usuario o Contraseña incorrecta”, “Error”,2); Desbloquear(); } }

else System.exit(0); } private class Cancelar implements ActionListener{ public void actionPerformed(ActionEvent Evento){ System.exit(0); } } }

import java.sql.*;

public class PRObBorrado{

PRObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM PRODUCTOS”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;
public class PRObConsulta{ private int Posicion=0; private PRObRegistro DatosPersona; PRObConsulta(String DNIPedido){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PRODUCTOS”);

Personas.moveToInsertRow(); while(Personas.next()){ String Num=Personas.getString(“Num_Prod”);

if(Num.equalsIgnoreCase(DNIPedido)){ Posicion=Personas.getRow(); String Nombre=Personas.getString(“Nom_Prod”); String Desc=Personas.getString(“Descripcion”); String Unidad=Personas.getString(“Unidad”); String Fing=Personas.getString(“Fecha_ingreso”); String Cmin=Personas.getString(“Cant_min”); String Cmax=Personas.getString(“Cant_max”); String Existencia=Personas.getString(“Existencia”); String Pprod=Personas.getString(“Precio_Prod”); String Pvta=Personas.getString(“Precio_Vta”);

DatosPersona=new PRObRegistro(Num,Nombre,Desc,Unidad,Fing,Cmin,Cmax,Existencia,Pprod,Pvta); break;

} }

Personas.close(); Conexion.close(); SentenciaSQL.close(); }

catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e); } } public int PosicionEncontrada(){ return Posicion;

}
public PRObRegistro DameDatos(){ return DatosPersona; }
}

import java.sql.*;

public class PRObInsercion{

PRObInsercion(PRObRegistro Datos){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos);
SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PRODUCTOS”);

Personas.moveToInsertRow();

Personas.updateString(“Num_Prod”,Datos.DameNum()); Personas.updateString(“Nom_Prod”,Datos.DameNombre()); Personas.updateString(“Descripcion”,Datos.DameDesc()); Personas.updateString(“Unidad”,Datos.DameUnidad()); Personas.updateString(“Fecha_ingreso”,Datos.DameFing()); Personas.updateString(“Cant_min”,Datos.DameCmin()); Personas.updateString(“Cant_max”,Datos.DameCmax()); Personas.updateString(“Existencia”,Datos.DameExistencia()); Personas.updateString(“Precio_Prod”,Datos.DamePprod()); Personas.updateString(“Precio_Vta”,Datos.DamePvta()); Personas.insertRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }
142Thread s, concurrent execution, and synchronization

import java.sql.*;

public class PRObModificacion{

PRObModificacion(int PosicionBuscada, PRObRegistro PRDatos){

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PRODUCTOS”); Personas.absolute(PosicionBuscada); Personas.updateString(“Num_Prod”,PRDatos.DameNum()); Personas.updateString(“Nom_Prod”,PRDatos.DameNombre()); Personas.updateString(“Descripcion”,PRDatos.DameDesc()); Personas.updateString(“Unidad”,PRDatos.DameUnidad()); Personas.updateString(“Fecha_ingreso”,PRDatos.DameFing()); Personas.updateString(“Cant_min”,PRDatos.DameCmin());

Personas.updateString(“Cant_max”,PRDatos.DameCmax()); Personas.updateString(“Existencia”,PRDatos.DameExistencia()); Personas.updateString(“Precio_Prod”,PRDatos.DamePprod()); Personas.updateString(“Precio_Vta”,PRDatos.DamePvta()); Personas.updateRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;

public class PRObPosicionamiento{

private PRObRegistro DatosPersona; private int Posicion;

PRObPosicionamiento(String Accion, int Posicion){ int IDAccion, Edad; String Num_Prod,Nom_Prod,Descripcion,Unidad,Fecha_ingreso,Can_min,Can_max,Existencia,Precio_Prod,Precio_Vta;

boolean PosicionCorrecta=false;

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”;

Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PRODUCTOS”);

Personas.absolute(Posicion);

IDAccion=Integer.parseInt(Accion); switch(IDAccion){ case 0: PosicionCorrecta=Personas.last(); break; case 1: PosicionCorrecta=Personas.first(); break; case 2: PosicionCorrecta=Personas.relative(-5); break; case 3: PosicionCorrecta=Personas.previous(); break; case 4: PosicionCorrecta=Personas.next(); break; case 5: PosicionCorrecta=Personas.relative(+5); break; }

if(PosicionCorrecta){ this.Posicion=Personas.getRow();

Num_Prod=Personas.getString(“Num_Prod”); Nom_Prod=Personas.getString(“Nom_Prod”); Descripcion=Personas.getString(“Descripcion”); Unidad=Personas.getString(“Unidad”); Fecha_ingreso=Personas.getString(“Fecha_ingreso”); Can_min=Personas.getString(“Can_min”); Can_max=Personas.getString(“Can_max”); Existencia=Personas.getString(“Existencia”); Precio_Prod=Personas.getString(“Precio_Prod”); Precio_Vta=Personas.getString(“Precio_Vta”);

} else{ this.Posicion=Posicion;

Num_Prod=”——-”; Nom_Prod=”——-”; Descripcion=”——-”; Unidad=”——-”; Fecha_ingreso=”——-”; Can_min=”——-”; Can_max=”——-”; Existencia=”——-”; Precio_Prod=”——-”; Precio_Vta=”——-”; } DatosPersona=new PRObRegistro(Num_Prod,Nom_Prod,Descripcion,Unidad,Fecha_ingreso,Can_min,Can_max,Existencia,Precio_Prod,Precio_Vta);

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){

System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } public int Posicion(){ return Posicion; } public PRObRegistro DameDatos(){ return DatosPersona; } }
public class PRObRegistro {
private String Num_Prod,Nom_Prod,Descripcion,Unidad,Fecha_ingreso,Can_min,Can_max,Existencia,Precio_Prod,Precio_Vta;
PRObRegistro (String Num_Prod,String Nom_Prod,String Descripcion,String Unidad,String Fecha_ingreso,String Can_min,String Can_max,String Existencia,String Precio_Prod,String Precio_Vta){

this.Num_Prod=Num_Prod;
this.Nom_Prod=Nom_Prod;
this.Descripcion=Descripcion;
this.Unidad=Unidad;
this.Fecha_ingreso=Fecha_ingreso;
this.Can_min=Can_min;
this.Can_max=Can_max;
this.Existencia=Existencia;
this.Precio_Prod=Precio_Prod;
this.Precio_Vta=Precio_Vta;

}
String DameNum(){
return Num_Prod;
}
String DameNombre(){
return Nom_Prod;
}
String DameDesc(){
return Descripcion;
}
String DameUnidad(){
return Unidad;
}
String DameFing(){
return Fecha_ingreso;
}
String DameCmin(){
return Can_min;
}
String DameCmax(){
return Can_max;
}
String DameExistencia(){
return Existencia;
}
String DamePprod(){
return Precio_Prod;
}
String DamePvta(){
return Precio_Vta;
}
}

16 Compilation, source file names, class names, and class files
A Java program consists of one or more source files (with filename suffix .java). A source file may
contain one or more class or interface declarations. A source file can contain only one declaration
of a public class or interface, which must then have the same name as the file (minus the filename
suffix). A source file source.java is compiled to Java class files (with filename suffix .class) by
a Java compiler, such as jikes or javac:
jikes source.java
This creates one class file for each class or interface declared in the source file source.java. A
class or interface C declared in a top-level declaration produces a class file called C.class. A nested
class or interface D declared inside class C produces a class file called C$D.class. A local class D
declared inside a method in class C produces a class file called C$1$D.class or similar.
A Java class C which declares the method public static void main(String[] args) can
be executed using the Java runtime system java by typing a command line of the form
java C arg1 arg2 …
This will execute the body of method main with the command line arguments arg1, arg2, . . . bound
to the array elements args0, args1, . . . of type String inside the method main. The program
in Example 6 concatenates all the command line arguments.
17 Packages
Java source files may be organized in packages. Every source file belonging to package p must begin
with the package declaration
package p;
and must be stored in a subdirectory called p. A class declared in a source file with no package
declaration belongs to the anonymous default package. A source file not belonging to package p
may refer to class C from package p by using the qualified name p.C, in which the class name is
prefixed by the package name. To use the unqualified class name without the package name prefix,
the source file must begin with an import declaration (possibly following a package declaration):
import p.C;
Alternatively, it may begin with an import declaration of the form:
import p.*;
after which all accessible class and interface names from package p can be used unqualified. The Java
class library package java.lang is implicitly imported into all source files. Hence all java.lang
classes, such as String and Math, can be referred to unqualified, without the package name.
Package names may be composite. For example, the Java class library package java.util
contains the class Vector, which is declared in file java/util/Vector.java. The qualified name
of that class is java.util.Vector; to avoid the package prefix, use one of these declarations:
import java.util.Vector;
import java.util.*;
Packages 61
Example 74 The vessel hierarchy as a package
The package vessel below contains part of the vessel hierarchy (Example 16). The fields in
classes Tank and Barrel are final, so they cannot be modified after object creation. They are
protected, so they are accessible in subclasses declared outside the vessel package, as shown in
file Usevessels.java below (which is in the anonymous default package, not the vessel package).
The file vessel/Vessel.java
package vessel;
public abstract class Vessel {
private double contents;
public abstract double capacity();
public final void fill(double amount)
{ contents = Math.min(contents + amount, capacity()); }
public final double getContents() { return contents; }
}
The file vessel/Tank.java
package vessel;
public class Tank extends Vessel {
protected final double length, width, height;
public Tank(double l, double w, double h) { length = l; width = w; height = h; }
public double capacity() { return length * width * height; }
public String toString()
{ return “tank (l,w,h) = (” + length + “, “ + width + “, “ + height + “)”; }
}
The file vessel/Barrel.java
package vessel;
public class Barrel extends Vessel {
protected final double radius, height;
public Barrel(double r, double h) { radius = r; height = h; }
public double capacity() { return height * Math.PI * radius * radius; }
public String toString() { return “barrel (r, h) = (” + radius + “, “ + height + “)”; }
}
The file Usevessels.java
Subclass Cube of class Tank may access the field length because that field is declared protected
in Tank above. The main method is unmodified from Example 17.
import vessel.*;
class Cube extends Tank {
public Cube(double side) { super(side, side, side); }
public String toString() { return “cube (s) = (” + length + “)”; }
}
class Usevessels {
public static void main(String[] args) { ... }
}
62 References
Notational conventions in this document
Symbol Meaning
v value of any type
x variable or parameter or field or array element
e expression
t type (base type or reference type)
s expression of type string
m method
f field
C class
E exception type
I interface
a expression or value of array type
o expression or value of object type
sig signature of method or constructor
p package
u expression or value of thread type
Subjects not covered in this document
Input and output; Garbage collection and finalization; Reflection; Details of IEEE754 floating-point
numbers.
18 References
At http://java.sun.com/docs/ and http://java.sun.com/j2se/ there is detailed documentation
for on-line browsing or downloading. Much documentation is available in print also:
_
The authoritative reference on the Java programming language is Gosling, Joy, Steele, Bracha:
The Java Language Specification, Second Edition, Addison-Wesley, June 2000 (544 pages).
Browse or download in HTML (573 KB) at http://java.sun.com/docs/books/jls/
_
An introduction to all aspects of Java programming is Arnold, Gosling, and Holmes: The Java
Programming Language, Third Edition, Addison-Wesley 2000 (624 pages).
_
The Java class libraries (or Java Core API) are described in two volumes: Chan, Lee, and
Kramer: The Java Class Libraries, Second Edition, Volume 1: java.io, java.lang, java.math,
java.net, java.text, java.util, Addison-Wesley 1998 (2050 pages); and Chan and Lee: The
Java Class Libraries, Second Edition, Volume 2: java.applet, java.awt, java.beans, Addison-
Wesley 1997 (1682 pages), plus a supplement: Chan, Lee, and Kramer: The Java Class Libraries:
1.2 Supplement, Addison-Wesley 1999 (1157 pages).
Class library version 1.3 can be browsed at http://java.sun.com/j2se/1.3/docs/api/
or downloaded at http://java.sun.com/j2se/1.3/docs.html (22 MB).
Index 63
19 Index
! (logical negation), 29
% (remainder), 29
& (bitwise and), 29, 30
& (logical strict and), 29, 30
&& (logical and), 29, 30

  • (multiplication), 29

+ (addition), 29
+ (string concatenation), 10 , 29
++ (increment), 29
+= (compound assignment), 29 – (minus sign), 29 – (subtraction), 29
— (decrement), 29
/ (division), 29
= (less than), 29
(left shift), 29, 30 (less than or equal to), 29
= (assignment), 29
== (equal to), 29, 30
> (greater than), 29
>= (greater than or equal to), 29
>> (signed right shift), 29, 30
>>> (unsigned right shift), 29, 30
?: (conditional expression), 29 , 32
^ (bitwise exclusive-or), 29, 30
^ (logical strict exclusive-or), 29, 30 | (bitwise or), 29, 30 | (logical strict or), 29, 30 || (logical or), 29, 30
~ (bitwise complement), 29, 30
abstract
class, 16
method, 20
abstract, see abstract
access modifiers, 18
accessible
class, 16
member, 18
actual parameter, 36
actual-list, 36
ambiguous method call, 21 , 38, 39
anonymous local class, 24
applicable method, 38
argument, 36
arithmetic operators, 30
ArithmeticException, 30 , 52
array, 12–13
access, 12
assignment to element, 12
creation, 12
element, 12
element type, 12
index, 12
initializer, 12
type, 6 , 12
ArrayIndexOutOfBoundsException, 12 , 52
ArrayStoreException, 12 , 52
ASCII character encoding, 10
assignment
compound, 29 , 32
expression, 32
operators, 32
statement, 41
to array element, 12
associative, 28, 29
base type, 6
block-statement, 41
boolean (base type), 6 , 40
Boolean class, 6
break statement, 46
byte (base type), 6 , 40
Byte class, 6
call-by-value, 36
case, 42
case sensitive, 4
cast, see type cast
catch, 48
catching an exception, 48
char (base type), 6 , 40
Character class, 6
charAt method (String), 10
checked exception, 52
class, 14–25
abstract, 16
anonymous local, 24
declaration, 14
64 Index
file, 4 , 60
final, 16
hierarchy, 16
inner, 14 , 24 , 32
libraries, 62
loading, 4 , 22 , 26
local, 14 , 24 , 60
member, 14
nested, 14 , 24 , 60
of an object, 26 , 28 , 32
public, 16 , 60
top-level, 14
Class class, 56
class-declaration, 14 , 50
class-modifier, 14
classbody, 14
ClassCastException, 40 , 52
comment, 4
compareTo method (String), 10
compatible types, 7
compilation, 4
compile-time constant, 42
compound assignment, 29 , 32
concat method (String), 10
concurrency, 54–59
conditional expression, 32
constant
compile-time, 42
constructor
call, 32
declaration, 22
default, 16 , 22
signature, 7 , 22
constructor-declaration, 22
constructor-modifier, 22
continue statement, 46
conversion, 40
narrowing, 40
widening, 40
core API, 62
Created (thread state), 55
current object, 14
currentThread method (Thread), 58
Dead (thread state), 55
decimal integer literal, 6
declaration
of class, 14
of constructor, 22
of field, 18
of formal parameter, 20
of interface, 50
of method, 20
of variable, 8
default
access, 18
constructor, 16 , 22
initial value
of array element, 12
of field, 18
package, 60
default
clause in switch, 42
division
by zero, 30
floating-point, 30
integer, 30
do-while statement, 44
double (base type), 6 , 40
Double class, 6
dynamic dispatch, 38
element
of array, 12
type, 12
else, 42
empty statement, 41
Enabled (thread state), 54, 55
enclosing object, 24 , 26
Enumeration interface, 25
equals method (String), 10
Error, 52
escape sequence, 10
Exception, 52
exception, 52–53
catching, 48
checked, 52
in static initializer, 22
throwing, 48
unchecked, 52
ExceptionInInitializerError, 22 , 52
execution, 4
expression, 28–40
aritmetic, 30
array access, 12
array creation, 12
Index 65
assignment, 32
conditional, 32
logical, 30
method call, 36–39
object creation, 32
type cast, 29 , 40
expression statement, 41
extended signature, 7
extends-clause, 16 , 50
field, 8 , 18
access, 34
declaration, 18
final, 18
static, 18
field-declaration, 18
field-desc-modifier, 50
field-description, 50
field-modifier, 18
final
class, 16
field, 18
method, 20
parameter, 20
variable, 8
final, see final
finally, 48
float (base type), 6 , 40
Float class, 6
floating-point
division, 30
literal, 6
overflow, 30
remainder, 30
for statement, 44
formal parameter, 20
formal-list, 20
hexadecimal integer literal, 6
if statement, 42
if-else statement, 42
IllegalMonitorStateException, 52 , 56
immediate superclass, 16
implements-clause, 50
import, 60
index into array, 12
IndexOutOfBoundsException, 52
initialization
of non-static fields, 18
of static fields, 18
initializer, 22
block, 22
of array type, 12
of field, 18
of variable, 8
initializer-block, 22
inner class, 14 , 24 , 32
inner object, 26
instance, 18
instance member, 14
instanceof, 29 , 32
int (base type), 6 , 40
integer
division, 30
literal, 6
overflow, 30
remainder, 30
Integer class, 6
interface, 50–51
declaration, 50
nested, 60
public, 50 , 60
interface-declaration, 50
interface-modifier, 50
interrupt method (Thread), 58
interrupted method (Thread), 58
interrupted status, 54 , 58
InterruptedException, 52
invocation of method, see method call
IOException, 52
isInterrupted method (Thread), 58
Java program, 60
join method (Thread), 58
Joining (thread state), 54, 55
label, 46
labelled statement, 46
lay-out of program, 4
left associative, 28
length
field (array), 12
method (String), 10
literal
base type, 6
floating-point, 6
66 Index
integer, 6
string, 10
loading of class, 22 , 26
local class, 14 , 24 , 60
lock, 56
Locking (thread state), 54, 55
logical operators, 30
long (base type), 6 , 40
Long class, 6
member, 14
instance, 14
static, 14
virtual, 14
member class, 14
non-static, 24
static, 24
method, 20
abstract, 20
body, 20
call, 36–39
ambiguous, 21 , 38, 39
signature, 36
statement, 41
declaration, 20
final, 20
invocation, see method call
non-static, 20
overloading, 20
overriding, 16
signature, 7 , 20
static, 20
method-declaration, 20
method-description, 50
method-modifier, 20
monitor, 56
more specific signature, 7
most specific signature, 7
name, 4
reserved, 4
named constant, 8 , 50
narrowing conversion, 40
nested class, 14 , 24 , 60
nested interface, 60
new
array creation, 12 , 29
object creation, 24 , 29 , 32
non-static
code, 14
field, 18
initializer block, 22
member class, 24
method, 20
notify method (Object), 58
notifyAll method (Object), 58
null, 6 , 8
and + with string, 10
NullPointerException, 10 , 38 , 48 , 52 ,
56
Number class, 6
numeric type, 6
object, 18 , 26–27
creation expression, 32
enclosing, 26
initialization, 22
inner, 26
Object class, 7 , 10 , 16 , 58
octal integer literal, 6
OutOfMemoryError, 52
overflow
floating-point, 30
integer, 30
overloading
of constructors, 22
of methods, 20
overriding a method, 16
package, 60–61
access, 18
default, 60
parameter, 8
actual, 36
final, 20
formal, 20
parameter-modifier, 20
Point class (example), 15
postdecrement, 29, 30
postincrement, 29, 30
precedence, 28
predecrement, 29, 30
preincrement, 29, 30
private member, 18
program lay-out, 4
promotion type, 28
Index 67
protected member, 18 , 61
public
class, 16 , 50 , 60
interface, 50 , 60
member, 18
reference type, 6
remainder
floating-point, 30
integer, 30
reserved name, 4
return statement, 46
returntype, 20
void, 20
right associative, 28 , 32
Runnable interface, 54 , 59
Running (thread state), 54, 55
RuntimeException, 52
scope, 8
of field, 8 , 14
of label, 46
of member, 14
of parameter, 8 , 20
of variable, 8
shadowing a field, 8
shared state, 54
shift operators, 30
short (base type), 6 , 40
Short class, 6
short-cut evaluation, 30
signature, 7
extended, 7
more specific, 7
most specific, 7
of constructor, 22
of method, 20
of method call, 36
subsumption, 7
sleep method (Thread), 58
Sleeping (thread state), 54, 55
source file, 60
SPoint class (example), 15
StackOverflowError, 52
start method (Thread), 58
state, 28 , 41
of thread, 54, 55
state shared, 54
statement, 41–49
assignment, 41
block, 41
break, 46
continue, 46
do-while, 44
empty, 41
for, 44
if, 42
if-else, 42
labelled, 46
method call, 41
return, 46
switch, 42
synchronized, 56
throw, 48
try-catch-finally, 48
while, 44
static
class, 50
code, 14
field, 18
initializer block, 22
member, 14
member class, 24
method, 20
static, see static
string, 10 , 10–11
comparison, 10 , 30
concatenation, 10 , 29
literal, 10
StringIndexOutOfBoundsException, 10 , 52
subclass, 16
subinterface, 50
subsumption, 7
subtype, 7
super
superclass constructor call, 16
superclass member access, 16
superclass, 16
supertype, 7
switch statement, 42
synchronization, 56–59
synchronized method, 56
synchronized statement, 56
this
68 Index
constructor call, 22
current object reference, 34
thread, 54 , 54–59
communication, 54
state, 54, 55
Thread class, 54 , 58
throw statement, 48
Throwable class, 48 , 52
throwing an exception, 48
throws, 20
throws-clause, 20
top-level class, 14
toString method, 10, 11 , 15 , 52
try-catch-finally statement, 48
type, 6–7
array, 6 , 12
base, 6
conversion, 40
numeric, 6
reference, 6
type cast
expression, 29 , 40
for base types, 40
for reference types, 40
unchecked exception, 52
Unicode character encoding, 10
value, 8
variable, 8
final, 8
variable-declaration, 8
variable-modifier, 8
virtual member, 14
void returntype, 20
wait method (Object), 58
Waiting (thread state), 54, 55
while statement, 44
widening conversion, 40
yield method (Thread), 58



[ Enlace | Sin comentarios :'( ] del.icio.us del.icio.us Estrella este post ***** General

Manual Java 2da. parte

mié 06 de abril, 2005 - 16:40

Estado de ánimo: X
Seguridad de entrada: PUBLICO

Example 53 Nested for loops
This program prints a four-line triangle of asterisks (*):
for (int i=1; i==4; i++) {
for (int j=1; j==i; j++)
System.out.print(”*”);
System.out.println();
}
Example 54 Array search using while loop
This method behaves the same as wdayno1 in Example 51:
static int wdayno2(String wday) {
int i=0;
while (i = wdays.length && ! wday.equals(wdays[i]))
i++;
// Now i >= wdays.length or wday equal to wdays[i]
if (i = wdays.length)
return i+1;
else
return -1; // Here used to mean ‘not found’
}
static final String[] wdays =
{ “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” };
Example 55 Infinite loop because of misplaced semicolon
Here a misplaced semicolon (;) creates an empty loop body statement, where the increment i++ is
not part of the loop. Hence it will not terminate, but loop forever:
int i=0;
while (i=10);
i++;
Example 56 Using do-while (but while is usually preferable)
Throw a die and compute sum until 5 or 6 comes up:
static int waitsum() {
int sum = 0, eyes;
do {
eyes = (int)(1 + 6 * Math.random());
sum += eyes;
} while (eyes = 5);
return sum;
}
46 Statements
12.6 Labelled statements, returns, exits and exceptions
12.6.1 The return statement
The simplest form of a return statement, without an expression argument, is:
return;
That form of return statement must occur inside the body of a method whose returntype is void, or
inside the body of a constructor. Execution of the return statement exits the method or constructor,
and continues execution at the place from which it was called.
Alternatively, a return statement may have an expression argument:
return expression;
That form of return statement must occur inside the body of a method (not constructor) whose
returntype is a supertype of the type of the expression. The return statement is executed as follows:
First the expression is evaluated to some value v. Then it exits the method, and continues execution
at the method call expression that called the method; the value of that expression will be v.
12.6.2 The labelled statement
A labelled statement has the form
label : statement
where label is an identifier. The scope of label is statement, where it can be used in connection with
break (Section 12.6.3) and continue (Section 12.6.4). It is illegal to re-use the same label inside
statement, unless inside a local class in statement.
12.6.3 The break statement
A break statement is legal only inside a switch or loop, and has one of the forms
break;
break label;
Executing break exits the inner-most enclosing switch or loop, and continues execution after that
switch or loop. Executing break label exits that enclosing statement which has label label, and
continues execution after that statement. Such a statement must exist in the inner-most enclosing
method or constructor or initializer block.
12.6.4 The continue statement
A continue statement is legal only inside a loop, and has one of the forms
continue;
continue label;
Executing continue terminates the current iteration of the inner-most enclosing loop, and continues
the execution at the step (in for loops; see Section 12.5.1), or the condition (in while and do-while
loops; see Sections 12.5.2 and 12.5.3). Executing continue label terminates the current iteration of
that enclosing loop which has label label, and continues the execution at the step or the condition.
There must be such a loop in the inner-most enclosing method or constructor or initializer block.
Statements 47
Example 57 Using return to terminate a loop early
This method behaves the same as wdayno2 in Example 54:
static int wdayno3(String wday) {
for (int i=0; i = wdays.length; i++)
if (wday.equals(wdays[i]))
return i+1;
return -1; // Here used to mean ‘not found’
}
Example 58 Using break to terminate a loop early
double prod = 1.0;
for (int i=0; i=xs.length; i++) {
prod *= xs[i];
if (prod 0.0) break; } Example 59 Using continue to start a new iteration This method decides whether query is a substring of target. When a mismatch between the strings is found, continue starts the next iteration of the outer for loop, thus incrementing j: static boolean substring1(String query, String target) { nextposition: for (int j=0; jtarget.length()-query.length(); j++) {
for (int k=0; k=query.length(); k++)
if (target.charAt(j+k) != query.charAt(k))
continue nextposition;
return true;
}
return false;
}
Example 60 Using break to exit a labelled statement block
This method behaves as substring1 from Example 59. It uses break to exit the entire statement
block labelled thisposition, thus skipping the first return statement and starting a new iteration
of the outer for loop:
static boolean substring2(String query, String target) {
for (int j=0; j==target.length()-query.length(); j++)
thisposition: {
for (int k=0; k=query.length(); k++)
if (target.charAt(j+k) != query.charAt(k))
break thisposition;
return true;
}
return false;
}
48 Statements
12.6.5 The throw statement
A throw statement has the form
throw expression;
where the type of expression must be a subtype of class Throwable (Section 14). The throw statement
is executed as follows: The expression is evaluated to obtain an exception object v. If it is
null, then the exception NullPointerException is thrown. Otherwise, the exception object v is
thrown. In any case, the enclosing block statement is terminated abnormally; see Section 14. The
thrown exception may be caught in a dynamically enclosing try-catch statement (Section 12.6.6).
If the exception is not caught, then the entire program execution will be aborted, and information
from the exception will be printed on the console (for example, at the command prompt, or in the
Java Console inside a web browser).
12.6.6 The try-catch-finally statement
A try-catch statement is used to catch (particular) exceptions thrown by the execution of a block
of code. It has the following form:
try
body
catch (E1 ×1) catchbody1
catch (E2 ×2) catchbody2
...
finally finallybody
where E1, E2, . . . are names of exception types, the x1, x2, . . . are variable names, and the body,
the catchbodyi and the finallybody are block-statements (Section 12.2). There can be zero or more
catch blocks, and the finally clause may be absent, but at least one catch or finally clause
must be present.
We say that Ei matches exception type E if E is a subtype of Ei (possibly equal to Ei).
The try-catch-finally statement is executed by executing the body. If the execution of body
terminates normally, or exits by return or break or continue (when inside a method or constructor
or switch or loop), then the catch blocks are ignored. If body terminates abnormally by throwing
exception e of class E, then the first matching Ei (if any) is located, variable xi is bound to e, and
the corresponding catchbodyi is executed. If there is no matching Ei, then the entire try-catch
statement terminates abnormally with exception e.
If a finally clause is present, then the finallybody will be executed regardless whether the
execution of body terminated normally, regardless whether body exited by executing return or
break or continue (when inside a method or constructor or switch or loop), regardless whether
any exception thrown by body was caught by the catch blocks, and regardless whether any new
exception was thrown during the execution of a catch body.
Statements 49
Example 61 Throwing an exception to indicate failure
Instead of returning the bogus error value -1 as in method wdayno3 above, throw an exception of
class WeekdayException (Example 67). Note the throws clause (Section 9.8) in the method header:
static int wdayno4(String wday) throws WeekdayException {
for (int i=0; i = wdays.length; i++)
if (wday.equals(wdays[i]))
return i+1;
throw new WeekdayException(wday);
}
Example 62 A try-catch block
This example calls the method wdayno4 (Example 61) inside a try-catch block that handles exceptions
of class WeekdayException (Example 67) and its superclass Exception. The second catch
clause will be executed (for example) if the array access args0 fails because there is no command
line argument (since ArrayIndexOutOfBoundsException is a subclass of Exception). If an exception
is handled, it is bound to the variable x, and printed by an implicit call (Section 7) to the
exception’s toString-method:
public static void main(String[] args) {
try {
System.out.println(args0 + “ is weekday number “ + wdayno4(args0));
} catch (WeekdayException x) {
System.out.println(“Weekday problem: “ + x);
} catch (Exception x) {
System.out.println(“Other problem: “ + x);
}
}
Example 63 A try-finally block
This method attempts to read three lines from a file, each containing a single floating-point number.
Regardless whether anything goes wrong during reading (premature end of file, ill-formed number),
the finally clause will close the readers before the method returns. It would do so even if the
return statement were inside the try block:
static double[] readRecord(String filename) throws IOException {
Reader freader = new FileReader(filename);
BufferedReader breader = new BufferedReader(freader);
double[] res = new double3;
try {
res0 = new Double(breader.readLine()).doubleValue();
res1 = new Double(breader.readLine()).doubleValue();
res2 = new Double(breader.readLine()).doubleValue();
} finally {
breader.close();
freader.close();
}
return res;
}
50 Interfaces
13 Interfaces
13.1 Interface declarations
An interface describes fields and methods, but does not implement them. An interface-declaration
may contain field descriptions, method descriptions, class declarations, and interface declarations.
The declarations in an interface may appear in any order:
interface-modifiers interface I extends-clause {
field-descriptions
method-descriptions
class-declarations
interface-declarations
}
An interface may be declared at top-level or inside a class or interface, but not inside a method or
constructor or initializer. At top-level, the interface-modifiers may be public, or absent. A public
interface is accessible also outside its package. Inside a class or interface, the interface-modifiers
may be static (always implicitly understood), and at most one of public, protected, or private.
The extends-clause may be absent or have the form
extends I1, I2, ...
where I1, I2, . . . are interface names. If the extends-clause is present, then interface I describes all
those members described by I1, I2, . . . , and interface I is a subinterface (and hence subtype) of
I1, I2, . . . . Interface I can describe additional fields and methods, but cannot override inherited
member descriptions.
A field-description in an interface declares a named constant, and must have the form
field-desc-modifiers type f = initializer;
where field-desc-modifiers is a list of static, final, and public; all of which are understood and
need not be given explicitly. The field initializer must be an expression involving only literals and
operators, and static members of classes and interfaces.
A method-description for method m must have the form:
method-desc-modifiers returntype m(formal-list) throws-clause;
where method-desc-modifiers is a list of abstract and public, both of which are understood and
need not be given explicitly.
A class-declaration inside an interface is always implicitly static and public.
13.2 Classes implementing interfaces
A class C may be declared to implement one or more interfaces by an implements-clause:
class C implements I1, I2, ...
classbody
In this case, C is a subtype (see Section 5.4) of I1, I2, and so on. The compiler will check that C
declares all the methods described by I1, I2, . . . , with exactly the prescribed signatures and return
types. A class may implement any number of interfaces. Fields, classes, and interfaces declared in
I1, I2, . . . can be used in class C.
Interfaces 51
Example 64 Three interface declarations
import java.awt.*;
interface Colored { Color getColor(); }
interface Drawable { void draw(Graphics g); }
interface ColoredDrawable extends Colored, Drawable {}
Example 65 Classes implementing interfaces
Note that the methods getColor and draw must be public because they are implicitly public in the
above interfaces.
class ColoredPoint extends Point implements Colored {
Color c;
ColoredPoint(int x, int y, Color c) { super(x, y); this.c = c; }
public Color getColor() { return c; }
}
class ColoredDrawablePoint extends ColoredPoint implements ColoredDrawable {
Color c;
ColoredDrawablePoint(int x, int y, Color c) { super(x, y, c); }
public void draw(Graphics g) { g.fillRect(x, y, 1, 1); }
}
class ColoredRectangle implements ColoredDrawable {
int x1, x2, y1, y2; // (x1, y1) upper left, (x2, y2) lower right corner
Color c;
ColoredRectangle(int x1, int y1, int x2, int y2, Color c)
{ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.c = c; }
public Color getColor() { return c; }
public void draw(Graphics g) { g.drawRect(x1, y1, x2-x1, y2-y1); }
}
Example 66 Using interfaces as types
static void printcolors(Colored[] cs) {
for (int i=0; i=cs.length; i++)
System.out.println(cs[i].getColor().toString());
}
static void draw(Graphics g, ColoredDrawable[] cs) {
for (int i=0; i=cs.length; i++) {
g.setColor(cs[i].getColor());
cs[i].draw(g);
}
}
52 Exceptions
14 Exceptions
An exception is an object of an exception type: a subclass of class Throwable. An exception is
used to signal and describe an abnormal situation during program execution. The evaluation of an
expression or the execution of a statement may terminate abnormally by throwing an exception,
either by executing a throw statement (Section 12.6.5) or by executing a primitive operation, such
as assignment to an array element, that may throw an exception.
A thrown exception may be caught in a dynamically enclosing try-catch statement (Section
12.6.6). A caught exception may be re-thrown by a throw statement. If the exception is not
caught, then the entire program execution will be aborted, and information from the exception will
be printed on the console (for example, at the command prompt, or in the Java Console inside a web
browser). What is printed on the console is determined by the exception’s toString method.
Checked and unchecked exception types
There are two kinds of exception types: checked (those that must be declared in the throws-clause
of a method or constructor; Section 9.8) and unchecked (those that need not). If the execution of
a method body can throw a checked exception of class E, then class E or a supertype of E must be
declared in the throws-clause of the method.
Some of the most important predefined exception types, and their status (checked or unchecked)
are shown below.
Throwable
Error unchecked
ExceptionInInitializerError |
OutOfMemoryError |
StackOverflowError |
Exception checked
InterruptedException |
IOException |
RuntimeException unchecked
ArithmeticException |
ArrayStoreException |
ClassCastException |
IllegalMonitorStateException |
IndexOutOfBoundsException |
ArrayIndexOutOfBoundsException |
StringIndexOutOfBoundsException |
NullPointerException |
Exceptions 53
Example 67 Declaring a checked exception class
This is the class of exceptions thrown by method wdayno4 (Example 61). Note the toString method
which is used when printing an uncaught exception on the console:
class WeekdayException extends Exception {
private String wday;
public WeekdayException(String wday)
{ this.wday = wday; }
public String toString()
{ return “Illegal weekday “ + wday; }
}
54 Threads, concurrent execution, and synchronization
15 Threads, concurrent execution, and synchronization
15.1 Threads and concurrent execution
The preceding chapters describe sequential program execution, in which expressions are evaluated
and statements are executed one after the other: we have considered only a single thread of execution,
where a thread is an independent sequential activity. A Java program may execute several threads
concurrently, that is, potentially overlapping in time. For instance, one part of a program may
continue computing while another part is blocked waiting for input; see Example 68.
Threads are created and manipulated using the Thread class and the Runnable interface, both
of which are part of the Java class library package java.lang.
To program a new thread, one must implement the method public void run() described by the
Runnable interface. One can do this by declaring a subclass U of class Thread (which implements
Runnable). To create a new thread, create an object u of class U, and to permit it to run, execute
u.start(). This enables the new thread, so that it can execute concurrently with the current thread;
see Example 68.
Alternatively, declare a class C that implements Runnable, create an object o of that class, create
a thread object u = new Thread(o) from o, and execute u.start(); see Example 72.
Threads can communicate with each other only via shared state, namely, by using and assigning
static fields, non-static fields, and array elements. By the design of Java, threads cannot use local
variables and method parameters for communication.
States and state transitions of a thread
A thread is alive if it has been started and has not died. A thread dies by exiting its run() method,
either by returning or by throwing an exception. A live thread is in one of the states Enabled (ready
to run), Running (actually executing), Sleeping (waiting for a timeout), Joining (waiting for another
thread to die), Locking (trying to get the lock on object o), or Waiting (for notification on object o).
The state transitions of a thread can be summarized by this table and the figure opposite:
From state To state Reason for the transition
Enabled Running the system schedules the thread for execution
Running Enabled the system preempts the thread and schedules another
Enabled the thread executes yield()
Waiting the thread executes o.wait(), thus releasing the lock on o
Locking the thread attempts to execute synchronized (o) { ... }
Sleeping the thread executes sleep()
Joining the thread executes u.join()
Running the thread was interrupted; sets the interrupted status of the thread
Dead the thread exited run() by returning or by throwing an exception
Sleeping Enabled the sleeping period expired
Enabled the thread was interrupted; throws InterruptedException when run
Joining Enabled the thread u being joined died, or the join timed out
Enabled the thread was interrupted; throws InterruptedException when run
Waiting Locking another thread executed o.notify() or o.notifyAll()
Locking the wait for the lock on o timed out
Locking the thread was interrupted; throws InterruptedException when run
Locking Enabled the lock on o became available and was given to this thread
Threads, concurrent execution, and synchronization 55
Example 68 Multiple threads
The main program creates a new thread, binds it to u, and starts it. Now two threads are executing
concurrently: one executes main, and another executes run. While the main method is blocked
waiting for keyboard input, the new thread keeps incrementing i. The new thread executes yield()
to make sure that the other thread is allowed to run (when not blocked).
class Incrementer extends Thread {
public int i;
public void run() {
for (;;) { // Forever
i++; // increment i
yield();
}
} }
class ThreadDemo {
public static void main(String[] args) throws IOException {
Incrementer u = new Incrementer();
u.start();
System.out.println(“Repeatedly press Enter to get the current value of i:”);
for (;;) {
System.in.read(); // Wait for keyboard input
System.out.println(u.i);
} } }
The states and state transitions of a thread
A thread’s transition from one state to another may be caused by a method call performed by the
thread itself (shown in the typewriter font), by a method call possibly performed by another thread
(shown in the slanted font); and by timeouts and other actions (shown in the default font):
Enabled Running
Locking o Waiting for o
interrupt()
timeout
o.notifyAll() o.notify()
Sleeping Dead Created
Joining u
got lock
on o attempting to lock o o.wait()
scheduled
preempted
yield()
u.join()
sleep()
interrupt()
timeout
timeout
interrupt() u died
start() dies
56 Threads, concurrent execution, and synchronization
15.2 Locks and the synchronized statement
When multiple concurrent threads access the same fields or array elements, there is considerable risk
of creating an inconsistent state; see Example 70. To avoid this, threads may synchronize the access
to shared state, such as objects and arrays. A single lock is associated with every object, array, and
class. A lock can be held by at most one thread at a time.
A thread may explicitly ask for the lock on an object or array by executing a synchronized
statement, which has this form:
synchronized (expression)
block-statement
The expression must have reference type. The expression must evaluate to a non-null reference
o; otherwise a NullPointerException is thrown. After the evaluation of the expression, the
thread becomes Locking on object o; see the figure on page 55. When the thread obtains the lock on
object o (if ever), the thread becomes Enabled, and may become Running so the block-statement is
executed. When the block-statement terminates or is exited by return or break or continue or by
throwing an exception, then the lock on o is released.
A synchronized non-static method declaration (Section 9.8) is a shorthand for a method whose
body has the form:
synchronized (this)
method-body
That is, the thread will execute the method body only when it has obtained the lock on the current
object. It will hold the lock until it leaves the method body, and release it at that time.
A synchronized static method declaration (Section 9.8) in class C is a shorthand for a method
whose body has the form:
synchronized (C.class)
method-body
That is, the thread will execute the method body only when it has obtained the lock on the object
C.class, which is the unique object of class Class associated with the class C. It will hold the lock
until it leaves the method body, and release it at that time.
Constructors and initializers cannot be synchronized.
Mutual exclusion is ensured only if all threads accessing a shared object lock it before use. For
instance, if we add an unsynchronized method roguetransfer to a bank object (Example 70), we
can no longer be sure that a thread calling the synchronized method transfer has exclusive access
to the bank object: any number of threads could be executing roguetransfer at the same time.
A monitor is an object whose fields are private and are manipulated only by synchronized methods
of the object, so that all field access is subject to synchronization; see Example 71.
If a thread u needs to wait for some condition to become true, or for a resource to become available,
it may release its lock on object o by calling o.wait(). The thread must own the lock on object
o, otherwise exception IllegalMonitorStateException is thrown. The thread u will be added to
a set of threads waiting for notification on object o. This notification must come from another thread
which has obtained the lock on o and which executes o.notify() or o.notifyAll(). The notifying
thread does not lose the lock on o. After being notified, u must obtain the lock on o again before
it can proceed. Thus when the call to wait returns, thread u will own the lock on o just as before the
call; see Example 71.
For detailed rules governing the behaviour of unsynchronized Java threads, see the Java Language Specification,
Chapter 17.
Threads, concurrent execution, and synchronization 57
Example 69 Mutual exclusion
A Printer thread forever prints a (-) followed by a (/). If we create and run two concurrent printer
threads using new Printer().start() and new Printer().start(), then only one of the threads
can hold the lock on object mutex at a time, so no other symbols can be printed between (-) and
(/) in one iteration of the for loop. Thus the program must print //-/-/-/-/-/ and so on.
However, if the synchronization is removed, it may print —//—/-/-//—// and so on. (The call
pause(n) pauses the thread for 200 ms, whereas pause(100,300) pauses between 100 and 300
ms. This is done only to make the inherent non-determinacy of unsynchronized concurrency more
easily observable).
class Printer extends Thread {
static Object mutex = new Object();
public void run() {
for (;;) {
synchronized (mutex) {
System.out.print(”-”);
Util.pause(100,300);
System.out.print(”/”);
}
Util.pause(200);
} } }
Example 70 Synchronized methods in an object
The bank object below has two accounts. Money is repeatedly being transferred from one account
to the other by clerks. Clearly the total amount of money should remain constant (at 30 euro). This
holds true when the transfer method is declared synchronized, because only one clerk can access the
accounts at any one time. If the synchronized declaration is removed, the sum will differ from 30
most of the time, because one clerk is likely to overwrite the other’s deposits and withdrawals .
class Bank {
private int account1 = 10, account2 = 20;
synchronized public void transfer(int amount) {
int new1 = account1 – amount;
Util.pause(10);
account1 = new1; account2 = account2 + amount;
System.out.println(“Sum is “ + (account1+account2));
} }
class Clerk extends Thread {
private Bank bank;
public Clerk(Bank bank) { this.bank = bank; }
public void run() {
for (;;) { // Forever
bank.transfer(Util.random(-10, 10)); // transfer money
Util.pause(200, 300); // then take a break
} } }
... Bank bank = new Bank();
... new Clerk(bank).start(); new Clerk(bank).start();
58 Threads, concurrent execution, and synchronization
15.3 Operations on threads
The current thread, whose state is Running, may call these methods among others. Further Thread
methods are described in the Thread section of the Java class library; see Section 18.
_
Thread.yield() changes the state of the current thread from Running to Enabled, and thereby
allows the system to schedule another Enabled thread, if any.
_
Thread.sleep(n) sleeps for n milliseconds: the current thread becomes Sleeping, and after
n milliseconds becomes Enabled. May throw InterruptedException if the thread is
interrupted while sleeping.
_
Thread.currentThread() returns the current thread object.
_
Thread.interrupted() returns and clears the interrupted status of the current thread: true
if it has been interrupted since the last call to Thread.interrupted(); otherwise false.
Let u be a thread (an object of a subclass of Thread). Then
_
u.start() changes the state of u to Enabled, so that its run method will be called when a
processor becomes available.
_
u.interrupt() interrupts the thread u: if u is Running or Enabled or Locking, then its interrupted
status is set to true. If u is Sleeping or Joining it will become Enabled, and if it is
Waiting it will become Locking; in these cases u will throw InterruptedException when
and if it becomes Running.
_
u.isInterrupted() returns the interrupted status of u (and does not clear it).
_
u.join() waits for thread u to die; may throw InterruptedException if the current thread
is interrupted while waiting.
_
u.join(n) works as u.join() but times out and returns after at most n milliseconds. There
is no indication whether the call returned because of a timeout or because u died.
Operations on locked objects
A thread which owns the lock on an object o may call the following methods, inherited by o from
class Object in the Java class library; see Section 18.
_
o.wait() releases the lock on o, changes its own state to Waiting, and adds itself to the
set of threads waiting for notification about o. When notified (if ever), the thread must obtain
the lock on o, so when the call to wait returns, it again has the lock on o. May throw
InterruptedException if the thread is interrupted while waiting.
_
o.wait(n) works as o.wait() except that the thread will change state to Locking after n milliseconds,
regardless whether there has been a notification on o or not. There is no indication
whether the state change was caused by a timeout or because of a notification.
_
o.notify() chooses an arbitrary thread among the threads waiting for notification about o (if
any), and changes its state to Locking. The chosen thread cannot actually get the lock on o
until the current thread has released it.
_
o.notifyAll() works as o.notify(), except that it changes the state to Locking for all
threads waiting for notification about o.
Threads, concurrent execution, and synchronization 59
Example 71 Producers and consumers communicating via a monitor
A Buffer has room for one integer, and has a method put for storing into the buffer (if empty) and
a method get for reading from the buffer (if non-empty); it is a monitor (page 56). A thread calling
get must obtain the lock on the buffer. If it finds that the buffer is empty, it calls wait to (release
the lock and) wait until something has been put into the buffer. If another thread calls put and thus
notify, then the getting thread will start competing for the buffer lock again, and if it gets it, will
continue executing. Here we have used a synchronized statement in the method body (instead of
making the method synchronized, as is normal for a monitor) to emphasize that synchronization,
wait and notify all work on the buffer object this:
class Buffer {
private int contents;
private boolean empty = true;
public int get() {
synchronized (this) {
while (empty)
try { this.wait(); } catch (InterruptedException x) {};
empty = true;
this.notify();
return contents;
} }
public void put(int v) {
synchronized (this) {
while (!empty)
try { this.wait(); } catch (InterruptedException x) {};
empty = false;
contents = v;
this.notify();
} }
}
Example 72 Graphic animation using the Runnable interface
Class AnimatedCanvas below is a subclass of Canvas, and so cannot be a subclass of Thread also.
Instead it declares a run method and implements the Runnable interface. The constructor creates a
Thread object u from the AnimatedCanvas object this, and then starts the thread. The new thread
executes the run method, which repeatedly sleeps and repaints, thus creating an animation.
class AnimatedCanvas extends Canvas implements Runnable {
AnimatedCanvas() { Thread u = new Thread(this); u.start(); }
public void run() { // from Runnable
for (;;) { // forever sleep and repaint
try { Thread.sleep(100); } catch (InterruptedException e) { }
...
repaint();
}
}
public void paint(Graphics g) { ... } // from Canvas
...
}
60 Packages
Example 73 The following example shows an application of the antriores capitulos includes the application of threads, to cronometrar, and connection of data base, taking as example a distributing company of equipment of I compute.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
public class Bienvenida extends Frame{ public int PosicionSearch=1; private Panel MiPanelPrincipal; private JFrame FormPrincipal; private TextArea AreaDeListadoBegin; static String[ ] BotonDialogoBegin = { “Aceptar”, “Cancelar” }; JScrollPane AgregarTabla;/// JPanel DatosPanel; JLabel lblUsuario; JTextField Usuario; JLabel lblContraseña; JTextField Contraseña;

public Bienvenida(){ MiPanelPrincipal=new Panel (new GridLayout (2,1)); Panel PanelCtrl=new Panel (new FlowLayout(FlowLayout.CENTER)); AreaDeListadoBegin=new TextArea(); AreaDeListadoBegin.setEnabled(false);

Button BotonDesbloquear=new Button(“Aceptar”);

Button BotonCancelar=new Button(“Cancelar”);

lblUsuario = new JLabel(” Nombre de Usuario: “, JLabel.LEFT); lblContraseña = new JLabel(“Contraseña: “, JLabel.LEFT); Usuario=new JTextField(15); Contraseña=new JTextField(15); JPanel EtiquetaPanel = new JPanel(false); EtiquetaPanel.setLayout(new GridLayout(2, 2)); DatosPanel = new JPanel(false); DatosPanel.setLayout(new BoxLayout(DatosPanel,BoxLayout.X_AXIS)); EtiquetaPanel.add(lblUsuario); EtiquetaPanel.add(Usuario); EtiquetaPanel.add(lblContraseña); EtiquetaPanel.add(Contraseña); DatosPanel.add(EtiquetaPanel);

AreaDeListadoBegin.setText(”“) ; AreaDeListadoBegin.append(” “); AreaDeListadoBegin.append(” “); AreaDeListadoBegin.append(” “); AreaDeListadoBegin.append(” “);

AreaDeListadoBegin.append(” “);

MiPanelPrincipal.add(AreaDeListadoBegin); MiPanelPrincipal.add(PanelCtrl);

PanelCtrl.add(BotonDesbloquear); PanelCtrl.add(BotonCancelar);

BotonCancelar.addActionListener(new Cancelar());

FormPrincipal = new JFrame(“PAPELERIA JELLO ‘’ A D S I J E L ‘’”); FormPrincipal.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);}}); FormPrincipal.setBackground(Color.lightGray); FormPrincipal.getContentPane().add(MiPanelPrincipal); Desbloquear(); }

public void Desbloquear() { if(JOptionPane.showOptionDialog(AgregarTabla, DatosPanel, “Datos de Usuario”, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, BotonDialogoBegin, BotonDialogoBegin0)==0){ Thread s, concurrent execution, and synchronization 69

Conexion InstanciaConsulta=new Conexion (Usuario.getText(),Contraseña.getText()); PosicionSearch=InstanciaConsulta.PosicionEncontrada();

if(PosicionSearch!=0){ FormPrincipal.pack(); FormPrincipal.setVisible(true); FormPrincipal.setBounds(200, 200, 450, 240); } else{ JOptionPane.showMessageDialog(null ,“Usuario o Contraseña incorrecta”, “Error”,2); Desbloquear(); } } else System.exit(0);
}

private class Cancelar implements ActionListener{ public void actionPerformed(ActionEvent Evento){ System.exit(0); } } public static void main (String [] args){ new Bienvenida(); }
}

import java.sql.*;
public class Conexion{ private int Posicion=0; Conexion(String RecibeUsuario,String RecibeContraseña){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM Contraseña”); Personas.moveToInsertRow(); while(Personas.next()){ String compUsuario=Personas.getString(“Usuario”); String compContraseña=Personas.getString(“Contraseña”);

if(compUsuario.equalsIgnoreCase(RecibeUsuario) && compContraseña.equalsIgnoreCase(RecibeContraseña)){ Posicion=Personas.getRow(); break; } }

Personas.close(); Conexion.close(); SentenciaSQL.close();

} catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e);

} } public int PosicionEncontrada(){ return Posicion;
}
}

import java.sql.*;

public class ObBorrado{

ObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close();

} catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }

import java.sql.*;

public class ObBorrado{

ObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;
public class ObConsulta{ private int Posicion=0; private ObRegistro DatosPersona; ObConsulta(String DNIPedido){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”); Personas.moveToInsertRow(); while(Personas.next()){ String Num=Personas.getString(“Num_Cli”);

if(Num.equalsIgnoreCase(DNIPedido)){ Posicion=Personas.getRow(); String Nombre=Personas.getString(“Nom_Cli”); String RFC=Personas.getString(“RFC_Cli”); String DIR=Personas.getString(“Dir_Cli”);

String TEL=Personas.getString(“Tel_Cli”); String Ciudad=Personas.getString(“Cd_Cli”); String CP=Personas.getString(“CP_Cli”);

DatosPersona=new ObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

break;

} }

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

}

catch(SQLException e){ System.out.println(e); } } public int PosicionEncontrada(){ return Posicion;

}
public ObRegistro DameDatos(){ return DatosPersona; }
}

import java.sql.*;

public class ObInsercion{

ObInsercion(ObRegistro Datos){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.moveToInsertRow(); Personas.updateString(“Num_Cli”,Datos.DameNum()); Personas.updateString(“Nom_Cli”,Datos.DameNombre());

Personas.updateString(“RFC_Cli”,Datos.DameRFC()); Personas.updateString(“Dir_Cli”,Datos.DameDIR()); Personas.updateString(“Tel_Cli”,Datos.DameTEL()); Personas.updateString(“Cd_Cli”,Datos.DameCiudad()); Personas.updateString(“CP_Cli”,Datos.DameCP()); Personas.insertRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }

import java.sql.*;

public class ObModificacion{

ObModificacion(int PosicionBuscada, ObRegistro Datos){

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”); Personas.absolute(PosicionBuscada); Personas.updateString(“Num_Cli”,Datos.DameNum()); Personas.updateString(“Nom_cli”,Datos.DameNombre()); Personas.updateString(“RFC_Cli”,Datos.DameRFC()); Personas.updateString(“Dir_Cli”,Datos.DameDIR()); Personas.updateString(“Tel_Cli”,Datos.DameTEL()); Personas.updateString(“Cd_Cli”,Datos.DameCiudad()); Personas.updateString(“CP_Cli”,Datos.DameCP()); Personas.updateRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;

public class ObPosicionamiento{

private ObRegistro DatosPersona; private int Posicion;

ObPosicionamiento(String Accion, int Posicion){ int IDAccion, Edad; String Num,Nombre,RFC,DIR,TEL,Ciudad,CP; boolean PosicionCorrecta=false;

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.absolute(Posicion);

IDAccion=Integer.parseInt(Accion); switch(IDAccion){ case 0: PosicionCorrecta=Personas.last(); break; case 1: PosicionCorrecta=Personas.first(); break; case 2: PosicionCorrecta=Personas.relative(-5); break; case 3: PosicionCorrecta=Personas.previous(); break; case 4: PosicionCorrecta=Personas.next(); break; case 5: PosicionCorrecta=Personas.relative(+5); break; }

if(PosicionCorrecta){

this.Posicion=Personas.getRow(); Num=Personas.getString(“Num_Cli”); Nombre=Personas.getString(“Nom_Cli”); RFC=Personas.getString(“RFC_Cli”); DIR=Personas.getString(“Dir_Cli”); TEL=Personas.getString(“Tel_Cli”); Ciudad=Personas.getString(“Cd_Cli”); CP=Personas.getString(“CP_Cli”); } else{ this.Posicion=Posicion;

Num=”——-”; Nombre=”——-”; RFC=”——-”; DIR=”——-”; TEL=”——-”; Ciudad=”——-”; CP=”——-”; } DatosPersona=new ObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e); } }

public int Posicion(){ return Posicion; }

public ObRegistro DameDatos(){ return DatosPersona; }

}

public class ObRegistro {
private String Num,Nombre,RFC,DIR,TEL,Ciudad,CP;

Thread s, concurrent execution, and synchronization 81

ObRegistro (String Num, String Nombre, String RFC, String DIR, String TEL, String Ciudad, String CP){

this.Num=Num;
this.Nombre=Nombre;

this.RFC=RFC;
this.DIR=DIR;
this.TEL=TEL;
this.Ciudad=Ciudad;
this.CP=CP;

}
String DameNum(){
return Num;
}
String DameNombre(){
return Nombre;
}
String DameRFC(){
return RFC;
}
String DameDIR(){
return DIR;
}
String DameTEL(){
return TEL;
}
String DameCiudad(){
return Ciudad;
}
String DameCP(){
return CP;

}
}

import java.sql.*;

public class PObBorrado{

PObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){

System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); }

} }

import java.sql.*;
public class PObConsulta{ private int Posicion=0; private PObRegistro DatosPersona; PObConsulta(String DNIPedido){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”); Personas.moveToInsertRow(); while(Personas.next()){ String Num=Personas.getString(“Num_Prov”); if(Num.equalsIgnoreCase(DNIPedido)){ Posicion=Personas.getRow(); String Nombre=Personas.getString(“Nom_Prov”); String RFC=Personas.getString(“RFC_Prov”); String DIR=Personas.getString(“Dir_Prov”); String TEL=Personas.getString(“Tel_Prov”); String Ciudad=Personas.getString(“Cd_Prov”); String CP=Personas.getString(“CP_Prov”);

DatosPersona=new PObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

break;

} }

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e);

} } public int PosicionEncontrada(){ return Posicion;

}
public PObRegistro DameDatos(){ return DatosPersona; }
}
import java.sql.*;

public class PObInsercion{

PObInsercion(PObRegistro PDatos){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”);

Personas.moveToInsertRow(); Personas.updateString(“Num_Prov”,PDatos.DameNum()); Personas.updateString(“Nom_Prov”,PDatos.DameNombre()); Personas.updateString(“RFC_Prov”,PDatos.DameRFC()); Personas.updateString(“Dir_Prov”,PDatos.DameDIR()); Personas.updateString(“Tel_Prov”,PDatos.DameTEL()); Personas.updateString(“Cd_Prov”,PDatos.DameCiudad()); Personas.updateString(“CP_Prov”,PDatos.DameCP()); Personas.insertRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }

import java.sql.*;

public class PObModificacion{

PObModificacion(int PosicionBuscada, PObRegistro PDatos){

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”); Personas.absolute(PosicionBuscada); Personas.updateString(“Num_Prov”,PDatos.DameNum()); Personas.updateString(“Nom_Prov”,PDatos.DameNombre()); Personas.updateString(“RFC_Prov”,PDatos.DameRFC()); Personas.updateString(“Dir_Prov”,PDatos.DameDIR()); Personas.updateString(“Tel_Prov”,PDatos.DameTEL()); Personas.updateString(“Cd_Prov”,PDatos.DameCiudad()); Personas.updateString(“CP_Prov”,PDatos.DameCP()); Personas.updateRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;

public class PObPosicionamiento{

private PObRegistro DatosPersona; private int Posicion;

PObPosicionamiento(String Accion, int Posicion){ int IDAccion, Edad; String Num,Nombre,RFC,DIR,TEL,Ciudad,CP; boolean PosicionCorrecta=false;

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”;

Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”);

Personas.absolute(Posicion);

IDAccion=Integer.parseInt(Accion); switch(IDAccion){ case 0: PosicionCorrecta=Personas.last(); break; case 1: PosicionCorrecta=Personas.first(); break; case 2: PosicionCorrecta=Personas.relative(-5); break; case 3: PosicionCorrecta=Personas.previous(); break; case 4: PosicionCorrecta=Personas.next(); break; case 5: PosicionCorrecta=Personas.relative(+5); break; } if(PosicionCorrecta){ this.Posicion=Personas.getRow(); Num=Personas.getString(“Num_Prov”); Nombre=Personas.getString(“Nom_Prov”); RFC=Personas.getString(“RFC_Prov”); DIR=Personas.getString(“Dir_Prov”); TEL=Personas.getString(“Tel_Prov”); Ciudad=Personas.getString(“Cd_Prov”); CP=Personas.getString(“CP_Prov”); } else{ this.Posicion=Posicion;

Num=”——-”; Nombre=”——-”; RFC=”——-”; DIR=”——-”; TEL=”——-”; Ciudad=”——-”; CP=”——-”; } DatosPersona=new PObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e); } }

public int Posicion(){ return Posicion; }

public PObRegistro DameDatos(){ return DatosPersona; }

}

public class PObRegistro {
private String Num,Nombre,RFC,DIR,TEL,Ciudad,CP;
PObRegistro (String Num, String Nombre, String RFC, String DIR, String TEL, String Ciudad, String CP){

this.Num=Num;
this.Nombre=Nombre;
this.RFC=RFC;
this.DIR=DIR;
this.TEL=TEL;
this.Ciudad=Ciudad;
this.CP=CP;

}
String DameNum(){

return Num;
}
String DameNombre(){
return Nombre;
}
String DameRFC(){
return RFC;
}
String DameDIR(){
return DIR;
}
String DameTEL(){
return TEL;
}
String DameCiudad(){
return Ciudad;
}
String DameCP(){
return CP;
}

}

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
import java.text.*; public class Principal extends Applet implements Runnable{

public int PosicionSearch=1; private boolean band=false; private Panel MiPanelPrincipal; private JFrame FormPrincipal; private TextArea AreaDeListadoBegin; static String[] BotonDialogoBegin = { “Aceptar”, “Cancelar” }; JPanel DatosPanel; JLabel lblUsuario; JTextField Usuario; JLabel lblContraseña; JTextField Contraseña;

private volatile Thread timer; // The thread that displays clock private volatile Thread Cronometro; private SimpleDateFormat formatter; // Formats the date displayed private String lastdate,lastdate2,lastdate3; // String to hold date displayed private Date currentDate; // Used to get date to display TextField txt1=new TextField(6); private TextField CampoNum_Cli; private TextField CampoNom_Cli; private TextField CampoRFC_Cli; private TextField CampoDir_Cli; private TextField CampoTel_Cli; private TextField CampoCd_Cli; private TextField CampoCP_Cli;

private TextField CampoNum_Prov; private TextField CampoNom_Prov; private TextField CampoRFC_Prov; private TextField CampoDir_Prov; private TextField CampoTel_Prov;

private TextField CampoCd_Prov; private TextField CampoCP_Prov;

private TextField CampoNum_Prod; private TextField CampoNom_Prod; private TextField CampoDescripcion; private TextField CampoUnidad; private TextField CampoFecha_ingreso; private TextField CampoCan_min; private TextField CampoCan_max; private TextField CampoExistencia; private TextField CampoPrecio_Prod; private TextField CampoPrecio_Vta;

private TextField NumeroProducto; private TextField NombreProducto; private TextField Descrip; private TextField Precio; private TextField Cant; private TextField Subtotal; private TextField Total;

JScrollPane AgregarTabla; static String[] BotonDialogo = { “ Si “,” No “ };

public int PosicionBuscada=1; public int PPosicionBuscada=1; public int PRPosicionBuscada=1;

private JScrollPane PanelTabla;

private JScrollPane PPanelTabla; private JScrollPane PRPanelTabla; private JScrollPane PanelTablaVarios; private JScrollPane PanelVentas;

private TipoTabla VariosTabla; private TipoTabla Tabla; private TipoTabla PTabla; private TipoTabla PRTabla;

private ListarJDBC BaseDeDato; private JFrame Formulario,Formulario2,Formulario3,Formulario4,Formulario5,Formulario6; private JPanel MiPanel,MiPanel2,MiPanel3,MiPanel4,MiPanel5; private JLabel etiqReloj,preg;

public Principal(){

MiPanelPrincipal=new Panel (new GridLayout (2,1)); Panel PanelCtrl=new Panel (new FlowLayout(FlowLayout.CENTER)); AreaDeListadoBegin=new TextArea(); AreaDeListadoBegin.setEnabled(false);

Button BotonDesbloquear=new Button(“Aceptar”);

Button BotonCancelar=new Button(“Cancelar”);

lblUsuario = new JLabel(” Nombre de Usuario: “, JLabel.LEFT); lblContraseña = new JLabel(“Contraseña: “, JLabel.LEFT); Usuario=new JTextField(15); Contraseña=new JTextField(15); JPanel EtiquetaPanel = new JPanel(false); EtiquetaPanel.setLayout(new GridLayout(2, 2)); DatosPanel = new JPanel(false); DatosPanel.setLayout(new BoxLayout(DatosPanel,BoxLayout.X_AXIS)); EtiquetaPanel.add(lblUsuario); EtiquetaPanel.add(Usuario); EtiquetaPanel.add(lblContraseña); EtiquetaPanel.add(Contraseña); DatosPanel.add(EtiquetaPanel);

AreaDeListadoBegin.setText(”“) ; AreaDeListadoBegin.append(“Autorizado a:ntt María Elena Fernández Márqueznn”); AreaDeListadoBegin.append(“tANÁLISIS Y DISEÑO DEL SISTEMA DE INFORMACION PARA LAn”);

AreaDeListadoBegin.append(“tttPAPELERIA JELANSA:nn”); AreaDeListadoBegin.append(“t’‘ A D S I J E L ‘’”); AreaDeListadoBegin.append(“nnntttB I E N V E N I D O”); MiPanelPrincipal.add(AreaDeListadoBegin); MiPanelPrincipal.add(PanelCtrl);

PanelCtrl.add(BotonDesbloquear); PanelCtrl.add(BotonCancelar);

BotonCancelar.addActionListener(new Cancelar());

etiqReloj=new JLabel(“Hora Actual:”); preg=new JLabel(“¿Realmente desea salir del Sistema ADSIJEL?”); MiPanel=new JPanel (new GridLayout (1,2)); MiPanel2=new JPanel (new GridLayout (1,1)); MiPanel3=new JPanel (new GridLayout (1,1)); MiPanel4=new JPanel (new GridLayout (1,1)); MiPanel5=new JPanel (new GridLayout (1,1));

Panel Panel1=new Panel (new GridLayout (1,1)); Panel Panel2=new Panel (new GridLayout (1,1)); Panel Panel3=new Panel (new GridLayout (1,1)); Panel Panel4=new Panel (new GridLayout (1,1));


Panel Panel5=new Panel (new GridLayout (1,1));

Panel PanelHora=new Panel (new GridLayout (6,1));

Panel PanelReloj=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PanelReloj2=new Panel (new FlowLayout(FlowLayout.CENTER));

Button SalirSistema=new Button(“Cerrar Sistema”); Button BotonProducto=new Button(“PRODUCTOS”); Button BotonVenta=new Button(“VENTAS”); Button BotonProveedor=new Button(“PROVEEDOR”); Button BotonCliente=new Button(“CLIENTES”); Button BotonVarios=new Button(“CLIENTES/PROVEEDORES”);

Panel1.add(BotonProducto); Panel2.add(BotonVenta); Panel3.add(BotonProveedor); Panel4.add(BotonCliente); Panel5.add(BotonVarios);

BotonCliente.addActionListener(new Cliente()); BotonProveedor.addActionListener(new Proveedor()); BotonProducto.addActionListener(new Producto());

Panel PanelIzq=new Panel (new GridLayout (9,1));

Panel PanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelRFC=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelDIR=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelTEL=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelCiudad=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelCP=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PPanelIzq=new Panel (new GridLayout (9,1)); Panel PPanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelRFC=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelDIR=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelTEL=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelCiudad=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelCP=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PRPanelIzq=new Panel (new GridLayout (12,1)); Panel PRPanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PRPanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelDes=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelUnidad=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelFing=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelCmin=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelCmax=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelExistencia=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelPprod=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelPvta=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel VtaPanelIzq=new Panel (new GridLayout (12,1)); Panel VtaPanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelDes=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelPrecio=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelCant=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelSub=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelTotal=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Panel PPanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PPanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Panel PRPanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PRPanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Panel VtaPanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel VtaPanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Label EtiquetaNum=new Label (“Numero”); Label EtiquetaNombre=new Label (“Nombre”); Label EtiquetaRFC=new Label (“RFC”); Label EtiquetaDIR=new Label (“Dirección”); Label EtiquetaTEL=new Label (“Telefono”); Label EtiquetaCiudad=new Label (“Ciudad”); Label EtiquetaCP=new Label (“Cod. Postal”);

Label EtiquetaPNum=new Label (“Numero”); Label EtiquetaPNombre=new Label (“Nombre”); Label EtiquetaPRFC=new Label (“RFC”); Label EtiquetaPDIR=new Label (“Dirección”); Label EtiquetaPTEL=new Label (“Telefono”); Label EtiquetaPCiudad=new Label (“Ciudad”); Label EtiquetaPCP=new Label (“Cod. Postal”);

Label EtiquetaNum_Prod=new Label (“Numero”); Label EtiquetaNom_Prod=new Label (“Nombre”); Label EtiquetaDescripcion=new Label (“Descripción”); Label EtiquetaUnidad=new Label (“Unidad”); Label EtiquetaFecha_ingreso=new Label (“Fecha Ingreso”); Label EtiquetaCan_min=new Label (“Cantidad Minima”); Label EtiquetaCan_max=new Label (“Cantidad Maxima”); Label EtiquetaExistencia=new Label (“Existencia”); Label EtiquetaPrecio_Prod=new Label (“Precio Producto”); Label EtiquetaPrecio_Vta=new Label (“Precio Venta”);

Label EtiquetaNum_ProdVta=new Label (“Numero”); Label EtiquetaNom_ProdVta=new Label (“Nombre”); Label EtiquetaDescripcionVta=new Label (“Descripción”); Label EtiquetaPrecio=new Label (“Precio”); Label EtiquetaCant=new Label (“Cantidad”); Label EtiquetaSub=new Label (“Subtotal”); Label EtiquetaTotal=new Label (“Total”);

CampoNum_Cli=new TextField (10); CampoNom_Cli=new TextField (30); CampoRFC_Cli=new TextField (15); CampoDir_Cli=new TextField (40); CampoTel_Cli=new TextField (12); CampoCd_Cli=new TextField (20); CampoCP_Cli=new TextField (10);

CampoNum_Prov=new TextField (10); CampoNom_Prov=new TextField (30); CampoRFC_Prov=new TextField (15); CampoDir_Prov=new TextField (40); CampoTel_Prov=new TextField (12); CampoCd_Prov=new TextField (20); CampoCP_Prov=new TextField (10);

CampoNum_Prod=new TextField (10); CampoNom_Prod=new TextField (30); CampoDescripcion=new TextField (30); CampoUnidad=new TextField (10); CampoFecha_ingreso=new TextField (10); CampoCan_min=new TextField (6); CampoCan_max=new TextField (6); CampoExistencia=new TextField (6); CampoPrecio_Prod=new TextField (6); CampoPrecio_Vta=new TextField (6);

NumeroProducto=new TextField (10); NombreProducto=new TextField (40); Descrip=new TextField (40); Precio=new TextField (10); Cant=new TextField (10); Subtotal=new TextField (12); Total=new TextField (12);

Button BotonConsultar=new Button(“Buscar”); Button BotonModificar=new Button(“Modificar”); Button BotonInsertar=new Button(“Insertar”);

Button BotonBorrar=new Button(“Borrar”); Button BotonListar=new Button(“Reporte”);

Button BotonPrimero=new Button(”|=”); BotonPrimero.setName(“1”); Button BotonMenosCinco=new Button(”—”); BotonMenosCinco.setName(“2”); Button BotonAnterior=new Button(”-”); BotonAnterior.setName(“3”); Button BotonSiguiente=new Button(”+”); BotonSiguiente.setName(“4”); Button BotonMasCinco=new Button(”++”); BotonMasCinco.setName(“5”); Button BotonUltimo=new Button(”>|”); BotonUltimo.setName(“0”);

Button BotonPConsultar=new Button(“Buscar”); Button BotonPModificar=new Button(“Modificar”); Button BotonPInsertar=new Button(“Insertar”); Button BotonPBorrar=new Button(“Borrar”); Button BotonPListar=new Button(“Reporte”);

Button BotonPPrimero=new Button(”|=”); BotonPPrimero.setName(“1”); Button BotonPMenosCinco=new Button(”—”); BotonPMenosCinco.setName(“2”); Button BotonPAnterior=new Button(”-”); BotonPAnterior.setName(“3”); Button BotonPSiguiente=new Button(”+”); BotonPSiguiente.setName(“4”); Button BotonPMasCinco=new Button(”++”); BotonPMasCinco.setName(“5”); Button BotonPUltimo=new Button(”>|”); BotonPUltimo.setName(“0”);

Button BotonPRConsultar=new Button(“Buscar”); Button BotonPRModificar=new Button(“Modificar”); Button BotonPRInsertar=new Button(“Insertar”); Button BotonPRBorrar=new Button(“Borrar”); Button BotonPRListar=new Button(“Reporte”);

Button BotonPRPrimero=new Button(”|=”); BotonPRPrimero.setName(“1”); Button BotonPRMenosCinco=new Button(”—”); BotonPRMenosCinco.setName(“2”); Button BotonPRAnterior=new Button(”-”); BotonPRAnterior.setName(“3”); Button BotonPRSiguiente=new Button(”+”); BotonPRSiguiente.setName(“4”); Button BotonPRMasCinco=new Button(”++”); BotonPRMasCinco.setName(“5”); Button BotonPRUltimo=new Button(”>|”); BotonPRUltimo.setName(“0”);

Button BotonBuscar=new Button(“Buscar”); Button BotonAgregar=new Button(“Agregar”);

PanelTabla = crearTabla(); PanelTabla.setBorder(new BevelBorder(BevelBorder.LOWERED)); PPanelTabla = PcrearTabla(); PPanelTabla.setBorder(new BevelBorder(BevelBorder.LOWERED));

PRPanelTabla = PRcrearTabla(); PRPanelTabla.setBorder(new BevelBorder(BevelBorder.LOWERED));

PanelTablaVarios= PRcrearTabla(); PanelTablaVarios.setBorder(new BevelBorder(BevelBorder.LOWERED));

PanelVentas= PRcrearTabla(); PanelVentas.setBorder(new BevelBorder(BevelBorder.LO



[ Enlace | Sin comentarios :'( ] del.icio.us del.icio.us Estrella este post ***** General

Manual Java

mié 06 de abril, 2005 - 16:30

Estado de ánimo: X
Seguridad de entrada: PUBLICO

Java Precisely
Version 1.05 of 2000-11-23
Peter Sestoft
Copyright c _ 2000
_
sestoft dina.kvl.dk
IT University of Copenhagen, Denmark
and
Royal Veterinary and Agricultural University, Copenhagen, Denmark
This document gives a concise description of the Java programming language, version 1.1 and later.
It is a quick reference for the reader who has already learnt (or is learning) Java from a standard
textbook and who wants to know the language in more detail.
The document presents general rules (on left-hand pages), and corresponding examples (on righthand
pages). All examples are fragments of legal Java programs. The complete examples are available
at the book website; see below.
This document is available at http://www.dina.kvl.dk/~sestoft/javaprecisely/
2
Contents
1 Running Java: compilation, loading, and execution 4
2 Names and reserved names 4
3 Java naming conventions 4
4 Comments and program lay-out 4
5 Types 6
5.1 Base types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.2 Reference types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.3 Array types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.4 Subtypes and compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5.5 Signatures and subsumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6 Variables, parameters, fields, and scope 8
6.1 Values bound to variables, parameters, or fields . . . . . . . . . . . . . . . . . . . . 8
6.2 Variable declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6.3 Scope of variables, parameters and fields . . . . . . . . . . . . . . . . . . . . . . . . 8
7 Strings 10
8 Arrays 12
8.1 Array creation and access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.2 Multi-dimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
8.3 Array initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9 Classes 14
9.1 Class declarations and class bodies . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
9.2 Top-level classes, nested classes, member classes and local classes . . . . . . . . . . 14
9.3 Class modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
9.4 The class modifiers public, final, and abstract . . . . . . . . . . . . . . . . . . 16
9.5 Subclasses, superclasses, class hierarchy, inheritance and overriding . . . . . . . . . 16
9.6 Field declarations in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
9.7 Member access modifiers: private, protected, public . . . . . . . . . . . . . . . 18
9.8 Method declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
9.9 Constructor declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
9.10 Initializer blocks, field initializers and initializers . . . . . . . . . . . . . . . . . . . 22
9.11 Nested classes, member classes, local classes, and inner classes . . . . . . . . . . . . 24
9.12 Anonymous classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
10 Classes and objects in the computer 26
11 Expressions 28
11.1 Arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
11.2 Logical operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
11.3 Bitwise operators and shift operators . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3
11.4 Assignment expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
11.5 Conditional expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
11.6 Object creation expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
11.7 Instance test expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
11.8 Field access expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
11.9 The current object reference this . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
11.10Method call expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
11.10.1 Method call: parameter passing . . . . . . . . . . . . . . . . . . . . . . . . 36
11.10.2 Method call: determining which method is called . . . . . . . . . . . . . . . 38
11.11Type cast expression and type conversion . . . . . . . . . . . . . . . . . . . . . . . 40
12 Statements 41
12.1 Expression statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12.2 Block statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12.3 The empty statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12.4 Choice statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
12.4.1 The if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
12.4.2 The if-else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
12.4.3 The switch statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
12.5 Loop statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
12.5.1 The for statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
12.5.2 The while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
12.5.3 The do-while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
12.6 Labelled statements, returns, exits and exceptions . . . . . . . . . . . . . . . . . . . 46
12.6.1 The return statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
12.6.2 The labelled statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
12.6.3 The break statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
12.6.4 The continue statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
12.6.5 The throw statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
12.6.6 The try-catch-finally statement . . . . . . . . . . . . . . . . . . . . . . 48
13 Interfaces 50
13.1 Interface declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
13.2 Classes implementing interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
14 Exceptions 52
15 Threads, concurrent execution, and synchronization 54
15.1 Threads and concurrent execution . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
15.2 Locks and the synchronized statement . . . . . . . . . . . . . . . . . . . . . . . . 56
15.3 Operations on threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
16 Compilation, source file names, class names, and class files 60
17 Packages 60
18 References 62
19 Index 63
4 Comments and program lay-out
1 Running Java: compilation, loading, and execution
Before a Java program can be executed, it must be compiled and loaded. The compiler checks that
the Java program is legal: that the program conforms to the syntax (grammar) for Java programs,
that operators (such as +) are applied to the correct type of operands (such as 5 and x), etc. If so, the
compiler generates so-called class files. Execution then starts by loading the needed class files.
Thus running a Java program involves three stages: compilation (checks that the program is
well-formed), loading (loads and initializes classes), and execution (runs the program code).
2 Names and reserved names
A legal name (of a variable, method, field, parameter, class, or interface) must start with a letter or
dollar sign ($) or underscore (_), and continue with zero or more letters or dollar signs or underscores
or digits (0–9). Do not use dollar signs in class names. Java is case sensitive: upper case letters are
distinguished from lower case letters. A legal name cannot be one of the following reserved names:
abstract boolean break byte case catch char class const continue
default do double else extends false final finally float for goto if
implements import instanceof int interface long native new null
package private protected public return short static strictfp super switch
synchronized this throw throws transient true try void volatile while
3 Java naming conventions
The following naming conventions are often followed in Java programs, although not enforced by
the compiler:
_
If a name is composed of several words, then each word (except possibly the first one) begins
with an upper case letter. Examples: setLayout, addLayoutComponent.
_
Names of variables, fields, and methods begin with a lower case letter. Examples: vehicle,
currentVehicle.
_
Names of classes and interfaces begin with an upper case letter. Examples: Layout, FlowLayout.
_
Named constants (that is, final variables and fields) are written entirely in upper case (and the
parts of composite names are separated by underscores _). Examples: CENTER, MAX_VALUE.
_
A package name is a sequence of dot-separated lower case names. Example: java.awt.event.
4 Comments and program lay-out
Comments have no effect on the execution of the program, but may be inserted anywhere to help
humans understand the program. There are two forms: one-line comments and delimited comments.
Program lay-out has no effect on the computer’s execution of the program, but is used to help
humans understand the structure of the program.
Comments and program lay-out 5
Example 1 Comments
class Comment {
// This is a one-line comment; it extends to the end of the line
/* This is a delimited comment,
extending over several lines */
int /* This is a delimited comment, extending over part of a line */ x = 117;
}
Example 2 Program lay-out style
class Layout { // Class declaration
int a;
Layout(int a)
{ this.a = a; } // One-line constructor body
int sum(int b) { // Multi-line method body
if (a > 0) // If statement
return a + b; // Single statement
else if (a < 0) { // Nested if-else, block statement
int res = -a + b;
return res * 117;
} else { // a 0 // Terminal else, block statement int sum = 0; for (int i=0; i= 1) && (day y) maxyz = z; else maxyz = y; } Example 4 Scope of fields, parameters, and variables class Scope { ... // void m1(int x) { // declaration of parameter x (#1) ... // x #1 in scope } // ... // void m2(int v2) { // ... // x #5 in scope } // ... // void m3(int v3) { // ... // x #5 in scope int x; // declaration of variable x (#2) ... // x #2 in scope } // ... // void m4(int v4) { // ... // x #5 in scope { // int x; // declaration of variable x (#3) ... // x #3 in scope } // ... // x #5 in scope { // int x; // declaration of variable x (#4) ... // x #4 in scope } // ... // x #5 in scope } // ... // int x; // declaration of field x (#5) ... // x #5 in scope } 10 Strings 7 Strings A string is an object of the predefined class String. A string literal is a sequence of characters within double quotes: "New York", "B52", and so on. Internally, a character is stored as a number using the Unicode character encoding, whose character codes 0–127 coincide with the ASCII character encoding. String literals and character literals may use character escape sequences: Escape code Meaning b backspace t horizontal tab n newline f form feed (page break) r carriage return " the double quote character ’ the single quote character the backslash character ddd the character whose character code is the three-digit octal number ddd udddd the character whose character code is the four-digit hexadecimal number dddd Each character escape sequence represents a single character. For example, the letter A has code 65 (decimal), which is written 101 in octal and 0041 in hexadecimal, so the string literal "A101u0041" is the same as "AAA". If s1 and s2 are expressions of type String then: _ s1.length() of type int is the length of s1, that is, the number of characters in s1. _ s1.equals(s2) of type boolean is true if s1 and s2 contain the same sequence of characters, false otherwise. _ s1.charAt(i) of type char is the character at position i in s1, counting from 0. If the index i is less than 0 or greater than s1.length(), then the exception StringIndexOutOfBoundsException is thrown. _ s1.concat(s2) of type String is a new string consisting of the characters of s1 followed by the characters of s2. _ s1.toString() of type String is just s1 itself. _ s1 + v is the same as s1.concat(Integer.toString(v)) when v has type int, and similarly for the other base types (Section 5.1). _ s1 + v is the same as s1.concat(v.toString()) when v has reference type and v is not null; and the same as s1.concat("null") when v is null. In particular, s1 + s2 is the same as s1.concat(s2) when s2 is not null. Any class C will inherit a default toString method from class Object (which produces strings of the form C 265734), but class C may override (redefine) it by declaring a method public String toString() to produce more useful strings. _ s1.compareTo(s2) returns a negative integer, zero, or a positive integer, according as s1 precedes, equals, or follows s2 in the usual lexicographical ordering based on the Unicode character encoding. If s1 or s2 is null, then the exception NullPointerException is thrown. _ more String methods are described in the Java class library String section; see Section 18. Strings 11 Example 5 Equality of strings String s1 = "abc"; String s2 = s1 + ""; // New object, but contains same text as s1 String s3 = s1; // Same object as s1 String s4 = s1.toString(); // Same object as s1 // The following statements print false, true, true, true, true: System.out.println("s1 and s2 identical objects: " + (s1 s2));
System.out.println(“s1 and s3 identical objects: “ + (s1 s3)); System.out.println("s1 and s4 identical objects: " + (s1 s4));
System.out.println(“s1 and s2 contain same text: “ + (s1.equals(s2)));
System.out.println(“s1 and s3 contain same text: “ + (s1.equals(s3)));
Example 6 Concatenate all command line arguments
public static void main(String[] args) {
String res = “”;
for (int i=0; is). The unsigned right shift n>>>s of a non-negative n equals n>>s; the
signed right shift of a negative n equals (n>>s)+(2s)+(2Lt y)
{ return y % 4 0 && y % 100 != 0 || y % 400 0; }
Example 36 Bitwise operators and shift operators
class Bitwise {
public static void main(String[] args) throws Exception {
int a = 0×3; // Bit pattern 0011
int b = 0×5; // Bit pattern 0101
println4(a); // Prints 0011
println4(b); // Prints 0101
println4(~a); // Prints 1100
println4(~b); // Prints 1010
println4(a & b); // Prints 0001
println4(a ^ b); // Prints 0110
println4(a | b); // Prints 0111
}
static void println4(int n) {
for (int i=3; i=0; i—)
System.out.print(n >> i & 1);
System.out.println();
}
}
32 Expressions
11.4 Assignment expression
In the assignment expression x = e, the type of e must be a subtype of the type of x. The type of the
expression is the same as the type of x. The assignment is executed by evaluating expression e and
storing its value in variable x, after a widening conversion (Section 11.11) if necessary. When e is a
compile-time constant of type byte, char, short or int, and x has type byte, char or short, then a
narrowing conversion is done automatically, provided the value of e is within the range representable
in x (Section 5.1). The value of the expression x = e is that of x after the assignment.
The assignment operator is right associative, so the multiple assignment x = y = e has the same
meaning as x = (y = e), that is, evaluate the expression e, assign its value to y, and then to x.
When e has reference type (object type or array type), then only a reference to the object or array
is stored in x. Thus the assignment x = e does not copy the object or array; see Example 38.
When x and e have the same type, the compound assignment x += e is equivalent to x = x + e;
however, x is evaluated only once, so in a[i++] += e the variable i is increment only once. When
the type of x is t, different from the type of e, then x += e is equivalent to x = (t)(x + e), in
which the intermediate result (x + e) is converted to type t (Section 11.11); again x is evaluated
only once. The other compound assignment operators -=, *=, and so on, are similar.
Since the value of the expression x += e is that of x after the assignment, and the assignment
operators associate to the right, one can write ps[i] = sum += e to first increment sum by e and
then store the result in ps[i]; see Example 27.
11.5 Conditional expression
The conditional expression e1 ? e2 : e3 is legal if e1 has type boolean, and e2 and e3 both have
numeric types, or both have type boolean, or both have compatible reference types. The conditional
expression is evaluated by first evaluating e1. If e1 evaluates to true, then e2 is evaluated; otherwise
e3 is evaluated. The resulting value is the value of the conditional expression.
11.6 Object creation expression
The object creation expression
new C(actual-list)
creates a new object of class C, by calling that constructor in class C whose signature matches the
arguments in actual-list.
The actual-list is evaluated from left to right to obtain a list of argument values. These argument
values are bound to the constructor’s parameters, an object of the class is created in the memory, the
non-static fields are given default initial values according to their type, a superclass constructor is
called (explicitly or implicitly), all non-static field initializers and initializer blocks are executed in
order of appearance, and finally the constructor body is executed to initialize the object. The value
of the constructor call expression is the newly created object, whose class is C.
When C is an inner class in class D, and o evaluates to an object of class D, then one may create a
C-object inside o using the syntax o.new C(actual-list); see Example 33.
11.7 Instance test expression
The instance test e instanceof t is evaluated by evaluating e to a value v. If v is not null and is
a reference to an object of class C, where C is a subtype of t, the result is true; otherwise false.
Expressions 33
Example 37 Assignment: widening, narrowing, and truncating compound assignment
The assignment d = 12 performs a widening of 12 from int to double. The assignments b = 123
and b2 = 123+1 perform an implicit narrowing from int to byte, because the right-hand sides
are compile-time constants. The assignment b2 = b1+1 would be illegal because b1+1 is not a
compile-time constant. The assignment b2 = 123+5 would be illegal because, although 123+5 is a
compile-time constant, its value is not representable as a byte (whose range is
_
128___ 127).
double d;
d = 12; // widening conversion from int to double
byte b1 = 123, b2; // narrowing conversion from int to byte
b2 = 123 + 1; // legal: 123+1 is a compile-time constant
b2 = (byte)(b1 + 1); // legal: (byte)(b1 + 1) has type byte
int x = 0;
x += 1.5; // equivalent to: x = (int)(x + 1.5); thus adds 1 to x
Example 38 Assignment does not copy objects
This example uses the Point class from Example 13. Assignment (and parameter passing) copies
only the reference, not the object:
Point p1 = new Point(10, 20);
System.out.println(“p1 is “ + p1); // prints: p1 is (10, 20)
Point p2 = p1; // p1 and p2 refer to same object
p2.move(8, 8);
System.out.println(“p2 is “ + p2); // prints: p2 is (18, 28)
System.out.println(“p1 is “ + p1); // prints: p1 is (18, 28)
Example 39 Compound assignment operators
Compute the product of all elements of array xs:
static double multiply(double[] xs) {
double prod = 1.0;
for (int i=0; i= 0 ? x : -x); }
Example 41 Object creation and instance test
Number n1 = new Integer(17);
Number n2 = new Double(3.14);
// The following statements print: false, true, false, true
System.out.println(“n1 is a Double: “ + (n1 instanceof Double));
System.out.println(“n2 is a Double: “ + (n2 instanceof Double));
System.out.println(“null is a Double: “ + (null instanceof Double));
System.out.println(“n2 is a Number: “ + (n2 instanceof Number));
34 Expressions
11.8 Field access expression
A field access must have one of these three forms
f
C.f
o.f
where C is a class and o an expression of reference type.
A class may have several fields of the same name f; see Section 9.6, Example 19, and Example 42
opposite.
A field access f must refer to a static or non-static field declared in or inherited by a class whose
declaration encloses the field access expression (not shadowed by a field in a nested enclosing class,
or by a variable or parameter of the same name). The class declaring the field is the target class TC.
A field access C.f must refer to a static field in class C or a superclass of C. That class is the
target class TC.
A field access o.f, where expression o has type C, must refer to a static or non-static field in class
C or a superclass of C. That class is the target class TC. To evaluate the field access, the expression o
is evaluated to obtain an object. If the field is static, then the object is ignored, and the value of o.f
is the TC-field f. If the field is non-static, then the value of o must be non-null, and the value of o.f
is found as the value of the TC-field f in object o.
It is informative to contrast non-static field access and non-static method call (Section 11.10):
_
In a non-static field access o.f, the field referred to is determined by the (compile-time) type
of the object expression o.
_
In a non-static method call o.m(...), the method called is determined by the (runtime) class
of the target object: the object to which o evaluates.
11.9 The current object reference this
The name this may be used in non-static code to refer to the current object (Section 9.1). When
non-static code in a given object is executed, the object reference this refers to the object as a
whole. Hence, when f is a field and m is a method (declared in the innermost enclosing class), then
this.f means the same as f (when f has not been shadowed by a variable or parameter of the same
name), and this.m(...) means the same as m(...).
When C is an inner class in an enclosing class D, then inside C the notation D.this refers to the
D object enclosing the inner C object. See Example 28 where TLC.this.nf refers to field nf of the
enclosing class TLC.
Expressions 35
Example 42 Field access
Here we illustrate static and non-static field access in the classes B, C and D from Example 19.
Note that the field referred to by an expression of form o.vf or o.sf is determined by the type of
expression o, not the class of the object to which o evaluates:
public static void main(String[] args) {
C c1 = new C(100); // c1 has type C; object has class C
B b1 = c1; // b1 has type B; object has class C
print(C.sf, B.sf); // Prints 102 121
print(c1.sf, b1.sf); // Prints 102 121
print(c1.vf, b1.vf); // Prints 100 120
C c2 = new C(200); // c2 has type C; object has class C
B b2 = c2; // b2 has type B; object has class C
print(c2.sf, b2.sf); // Prints 202 221
print(c2.vf, b2.vf); // Prints 200 220
print(c1.sf, b1.sf); // Prints 202 221
print(c1.vf, b1.vf); // Prints 100 120
D d3 = new D(300); // d3 has type D; object has class D
C c3 = d3; // c3 has type C; object has class D
B b3 = d3; // b3 has type B; object has class D
print(D.sf, C.sf, B.sf); // Prints 304 304 361
print(d3.sf, c3.sf, b3.sf); // Prints 304 304 361
print(d3.vf, c3.vf, b3.vf); // Prints 300 340 360
}
static void print(int x, int y) { System.out.println(x+” “+y); }
static void print(int x, int y, int z) { System.out.println(x+” “y“ “+z); }
Example 43 Using this when referring to shadowed fields
A common use of this is to refer to fields (this.x and this.y) that have been shadowed by
parameters (x and y), especially in constructors; see the Point class (Example 13):
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
... }
Example 44 Using this to pass the current object to a method
In the SPoint class (Example 14), the current object reference this is used in the constructor to add
the newly created object to the vector allpoints, and it is used in the method getIndex to look up
the current object in the vector:
class SPoint {
static Vector allpoints = new Vector();
int x, y;
SPoint(int x, int y) { allpoints.addElement(this); this.x = x; this.y = y; }
int getIndex() { return allpoints.indexOf(this); }
... }
36 Expressions
11.10 Method call expression
A method call expression, or method invocation, must have one of these four forms:
m(actual-list)
super.m(actual-list)
C.m(actual-list)
o.m(actual-list)
where m is a method name, C is a class name, and o is an expression of reference type. The actual-list
is a possibly empty comma-separated list of expressions, called the arguments or actual parameters.
The call signature is csig
_
m(t1, . . . , tn) where (t1, . . . , tn) is the list of types of the n arguments
in the actual-list.
Determining what method is actually called by a method call is moderately complicated because
(1) method names may be overloaded, each version of the method having a distinct signature; (2)
methods may be overridden, that is, re-implemented in subclasses; (3) non-static methods are called
by dynamic dispatch, given a target object; and (4) a method call in a nested class may call a method
declared in some enclosing class.
Section 11.10.1 describes argument evaluation and parameter passing, assuming the simple case
where it is clear which method m is being called. Section 11.10.2 then describes how to determine
which method is being called in the general case.
11.10.1 Method call: parameter passing
Here we consider the evaluation of a method call m(actual-list) when it is clear which method m is
called, and focus on the parameter passing mechanism.
The call is evaluated by evaluating the expressions in the actual-list from left to right to obtain
the argument values. These argument values are then bound to the corresponding parameters in the
method’s formal-list, in order of appearance. A widening conversion (see Section 11.11) occurs if
the type of an argument expression is a subtype of the method’s corresponding parameter type.
Java uses call-by-value to bind argument values to formal parameters, so the formal parameter
holds a copy of the argument value. Thus if the method changes the value of a formal parameter,
this change does not affect the argument. For an argument of reference type, the parameter holds a
copy of the object or array reference, and hence the parameter refers to the same object or array as
the actual argument expression. Thus if the method changes that object or array, the changes will be
visible after the method returns (see Example 46).
A non-static method must be called with a target object, for example as o.m(actual-list), where
the target object is the value of o, or as m(actual-list) where the target object is the current object
reference this. In either case, during execution of the method body, this will be bound to the target
object.
A static method is not called with a target object, and it is illegal to use the identifier this inside
the method body.
When the argument values have been bound to the formal parameters, then the method body is
executed. The value of the method call expression is the value returned by the method if its returntype
is non-void; otherwise the method call expression has no value. When the method returns, all
parameters and local variables in the method are discarded.
Expressions 37
Example 45 Calling non-overloaded, non-overridden methods
This program uses the SPoint class from Example 14. The static methods getSize and getPoint
may be called by prefixing them with the class name SPoint or an expression of type SPoint, such
as q. They may be called before any objects have been created. The non-static method getIndex
must be called with an object, as in r.getIndex(); then the method is executed with the current
object reference this bound to r.
public static void main(String[] args) {
System.out.println(“Number of points created: “ + SPoint.getSize());
SPoint p = new SPoint(12, 123);
SPoint q = new SPoint(200, 10);
SPoint r = new SPoint(99, 12);
SPoint s = p;
q = null;
System.out.println(“Number of points created: “ + SPoint.getSize());
System.out.println(“Number of points created: “ + q.getSize());
System.out.println(“r is point number “ + r.getIndex());
for (int i=0; i= 0)
return x;
else
return -x;
}
Example 51 A sequence of if-else statements
We cannot use a switch here, because a switch can work only on integer types (including char):
static int wdayno1(String wday) {
if (wday.equals(“Monday”)) return 1;
else if (wday.equals(“Tuesday”)) return 2;
else if (wday.equals(“Wednesday”)) return 3;
else if (wday.equals(“Thursday”)) return 4;
else if (wday.equals(“Friday”)) return 5;
else if (wday.equals(“Saturday”)) return 6;
else if (wday.equals(“Sunday”)) return 7;
else return -1; // Here used to mean ‘not found’
}
Example 52 switch statement
Below we could have used a sequence of if-else statements, but a switch is both faster and clearer:
static String findCountry(int prefix) {
switch (prefix) {
case 1: return “North America”;
case 44: return “Great Britain”;
case 45: return “Denmark”;
case 299: return “Greenland”;
case 46: return “Sweden”;
case 7: return “Russia”;
case 972: return “Israel”;
default: return “Unknown”;
}
}
44 Statements
12.5 Loop statements
12.5.1 The for statement
A for statement has the form
for (initialization; condition; step)
body
where the initialization is a variable-declaration (Section 6.2) or an expression, condition is an
expression of type boolean, step is an expression, and body is a statement. More generally, the
initialization and step may also be comma-separated lists of expressions; the expressions in each
such list are evaluated from left to right. The initialization, condition and step may be empty. An
empty condition is equivalent to true. Thus for (;;) body means ‘forever execute body’.
The for statement is executed as follows:
1. The initialization is executed
2. The condition is evaluated. If it is false, the loop terminates.
3. If it is true, then
(a) The body is executed
(b) The step is executed
(c) Execution continues at 2.
12.5.2 The while statement
A while statement has the form
while (condition)
body
where the condition is an expression of type boolean, and body is a statement. The while statement
is executed as follows:
1. The condition is evaluated. If it is false, the loop terminates.
2. If it is true, then
(a) The body is executed
(b) Execution continues at 1.
12.5.3 The do-while statement
A do-while statement has the form
do
body
while (condition);
where the condition is an expression of type boolean, and body is a statement. The body is executed
at least once, because the do-while statement is executed as follows:
1. The body is executed.
2. The condition is evaluated. If it is false, the loop terminates.
3. If it is true, then execution continues at 1.
Statements 45



[ Enlace | Sin comentarios :'( ] del.icio.us del.icio.us Estrella este post ***** General

RSS
Blog | Comentarios