0% acharam este documento útil (0 voto)
12 visualizações

Programacao Java

O documento é um guia abrangente sobre a linguagem de programação Java, abordando desde a orientação a objetos até o acesso a bancos de dados via JDBC. Ele inclui tópicos como fundamentos da linguagem, manipulação do JDK, tratamento de exceções, e desenvolvimento de interfaces gráficas com AWT e Swing. Além disso, apresenta exemplos práticos e conceitos avançados como threads e sockets.

Enviado por

robertomartins
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
12 visualizações

Programacao Java

O documento é um guia abrangente sobre a linguagem de programação Java, abordando desde a orientação a objetos até o acesso a bancos de dados via JDBC. Ele inclui tópicos como fundamentos da linguagem, manipulação do JDK, tratamento de exceções, e desenvolvimento de interfaces gráficas com AWT e Swing. Além disso, apresenta exemplos práticos e conceitos avançados como threads e sockets.

Enviado por

robertomartins
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu, reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 89

Pag.

: 2
Pag.: 3
Pag.: 4
PREFÁCIO ........................................................................................................................... 2
AGRADECIMENTOS ......................................................................................................... 3
ÍNDICE.................................................................................................................................. 4
1. ORIENTAÇÃO A OBJETOS ......................................................................................... 8
2. INTRODUÇÃO AO JAVA............................................................................................ 12
2.1 HISTÓRICO ................................................................................................................... 12
2.2 WEB X APLICATIVOS ...................................................................................................... 13
2.3 JAVA DEVELOPEMENT KIT - JDK .................................................................................. 13
2.4 MANIPULAÇÃO DO JDK(JAVA DEVELOPEMENT KIT) .................................................. 14
2.5 CARACTERÍSTICAS DA LINGUAGEM................................................................................. 15
2.6 COMPILAÇÃO DOS PROGRAMAS .................................................................................... 17
2.6.1 COMPILAÇÃO JAVA.................................................................................................... 17
2.6.2 COMPILAÇÃO DE OUTRAS LINGUAGENS ...................................................................... 17
2.7 AMBIENTES INTEGRADOS DE DESENVOLVIMENTO ........................................................... 17
2.7 AMBIENTES INTEGRADOS DE DESENVOLVIMENTO ........................................................... 18
2.8 INSTALAÇÃO DO COMPILADOR/INTERPRETADOR ( JDK ) ................................................ 18
2.9 ESTRUTURA DAS APLICAÇÕES JAVA................................................................................ 19
2.9.1 Elementos da Aplicação ...................................................................................... 20
Passagem de Parâmetros da Linha de Comando......................................................... 21
3. FUNDAMENTOS DA LINGUAGEM ......................................................................... 22
3.1 COMENTÁRIOS ............................................................................................................. 22
3.2 PALAVRAS CHAVES ..................................................................................................... 22
3.3 TIPOS DE DADOS .......................................................................................................... 23
3.4 VARIAVEIS OU ATRIBUTOS ........................................................................................... 23
3.5 CONSTANTES ............................................................................................................... 24
3.6 OPERADORES ............................................................................................................... 24
3.6.1 Operadores Aritméticos....................................................................................... 24
3.6.2 Operadores Relacionais ...................................................................................... 24
3.6.3 Operadores Lógicos ............................................................................................ 25
3.6.4 Atribuição Composta........................................................................................... 25
3.6.5 Operadores Incremental e Decremental ............................................................. 25
3.6.6 Operador Ternário .............................................................................................. 26
O VALOR DE A SERA “MENOR ”, VISTO QUE 1 E MENOR QUE 2. .......................................... 26
3.7 CONVERSÕES COM TIPOS PRIMITIVOS.......................................................................... 26
3.8 CONTROLE DE FLUXO .................................................................................................. 28
3.8.1 Sentenças Condicionais....................................................................................... 28
3.8.2 Loops Indeterminados ......................................................................................... 29
3.8.3 Loops Determinados............................................................................................ 29
3.8.4 Múltiplas Seleções ............................................................................................... 30
3.8.5 Manipulações diversas ........................................................................................ 30

Pag.: 5
3.9 ARRAYS ....................................................................................................................... 31
3.10 STRINGS ..................................................................................................................... 32
4. ORIENTAÇÃO A OBJETOS EM JAVA .................................................................... 33
4.1 VANTAGENS DA OO EM JAVA ...................................................................................... 33
4.2 COMPONENTES DA ORIENTAÇÃO A OBJETOS ............................................................... 33
4.2.1 Atributos (Variáveis) ........................................................................................... 34
4.2.2. Escopo de variáveis ............................................................................................ 35
4.2.3 Métodos ............................................................................................................... 35
#Modificadores de Acesso ............................................................................................ 37
4.2.4 Classes ................................................................................................................. 37
4.2.5 Pacote .................................................................................................................. 38
4.2.6 Objetos................................................................................................................. 39
4.3 ATRIBUTOS DE INSTANCIA ........................................................................................... 40
4.4 METODOS DE INSTANCIA ............................................................................................. 40
4.5 ATRIBUTOS E MÉTODOS ESTÁTICOS (STATIC FIELDS / STATIC METHODS) .................. 41
4.5.1 Atributos Estáticos............................................................................................... 41
4.5.2 Métodos Estáticos ou Métodos de Classe ........................................................... 41
4.6 PASSAGEM DE PARAMETROS: POR VALOR E POR REFERENCIA ...................................... 43
4.7 HERANÇA .................................................................................................................... 44
4.8 CLASSES E MÉTODOS FINAL ........................................................................................ 48
4.9 CLASSES E MÉTODOS ABSTRATOS ............................................................................... 48
4.10 CONVERSÕES EXPLICITAS E IMPLICITAS .................................................................... 49
4.11 INTERFACES ............................................................................................................... 51
5. TRATAMENTO DE EXCEÇÕES ............................................................................... 52
5.1 CRIANDO UMA EXCEÇÃO ............................................................................................. 53
5.2 CLAUSULA THROWS .................................................................................................... 54
6. ABSTRACT WINDOW TOOLKIT - AWT ................................................................ 56
6.1 ELEMENTOS DA INTERFACE AWT ............................................................................... 58
6.2 TRATAMENTO DE EVENTOS ......................................................................................... 60
6.2.1 Classes de Eventos .............................................................................................. 61
6.2.2 Tratadores de Eventos ou Listeners .................................................................... 61
6.2.3 Classe Adapter..................................................................................................... 62
6.3 COMPONENTES E EVENTOS SUPORTADOS .................................................................... 63
7. INTERFACE GRÁFICA - SWING.............................................................................. 64
7.1 FRAMES ....................................................................................................................... 65
8. APPLETS ........................................................................................................................ 67
8.1 HIERARQUIA ................................................................................................................ 67
8.2 ESTRUTURA ................................................................................................................. 67
8.3 ARQUIVOS HTML ....................................................................................................... 68
8.4 EXECUTANDO UM APPLET ........................................................................................... 68
8.4.1 Passagem de Parâmetros .................................................................................... 68
8.6 RESTRIÇÕES DE SEGURANÇA ....................................................................................... 69

Pag.: 6
8.7 PRINCIPAIS MÉTODOS .................................................................................................. 69
8.8 OBJETO GRÁFICO – CLASSE JAVA.AWT.GRAPHICS........................................................ 70
8.9 FONTES ........................................................................................................................ 70
8.10 CORES........................................................................................................................ 70
9. PROCESSAMENTO CONCORRENTE - THREADS .............................................. 72
9.1 SINCRONIZAÇÃO .......................................................................................................... 75
10. SOCKETS ..................................................................................................................... 77
10.1 CLASSE SERVERSOCKET ............................................................................................ 78
10.2 CLASSE SOCKET ........................................................................................................ 78
11. ACESSO A BANCO DE DADOS - JDBC ................................................................. 80
11.1 VERSÕES DO JDBC.................................................................................................... 81
11.1.1 JDBC 1.0 ........................................................................................................... 81
11.1.2 JDBC 2.0 ........................................................................................................... 81
11.1.3 JDBC 3.0 ........................................................................................................... 81
11.2 TIPOS DE DRIVERS ..................................................................................................... 81
11.2.1 Driver JDBC Tipo 1 .......................................................................................... 81
11.2.2 Driver JDBC Tipo 2 .......................................................................................... 82
11.2.3 Driver JDBC Tipo 3 .......................................................................................... 82
11.2.4 Driver JDBC Tipo 4 .......................................................................................... 83
11.3 CLASSES DO JDBC – CONEXÃO COM O BD ............................................................... 83
11.3.1 Driver ................................................................................................................ 83
11.3.2 DriverManager.................................................................................................. 83
11.3.3 java.sql.Connection ........................................................................................... 84
11.4 CLASSES JDBC – ACESSO AO BD.............................................................................. 84
11.4.1 java.sql.Statement.............................................................................................. 84
11.4.2 java.sql.ResultSet............................................................................................... 85
11.4.3 java.sql.PreparedStatement............................................................................... 85
11.5 JDBC 2.0................................................................................................................... 86
11.5.1 Scrollable ResultSet........................................................................................... 86
11.5.2 Atualizações de Dados via Programação ......................................................... 87
11.5.3 Consultas com o SQL 3 ..................................................................................... 87
12. REFERÊNCIAS BIBLIOGRÁFICAS ....................................................................... 88
LINKS ................................................................................................................................ 88
LIVROS .............................................................................................................................. 88
13. BIBLIOGRAFIA DOS AUTORES............................................................................. 89

Pag.: 7
Orientação a Objetos

Pag.: 8
Orientação a Objetos

Mensagem

Objeto B Objeto A

Pag.: 9
Orientação a Objetos

PESSOA
cor_de_olho
cor_de_cabelo
idade
pinta_cor_cabelo()
faz_aniversario()

Pag.: 10
Orientação a Objetos

Pag.: 11
Pag.: 12
Pag.: 13
Pag.: 14
Pag.: 15
Runtime.gc();
System.gc();

Pag.: 16
Pag.: 17
Pag.: 18
class NomeDaClasse {
// Atributos
// Métodos
public static void main( String[] args ) {
//corpo principal do programa
}
}

class OlaMundo {
public static void main( String[] args ) {
//corpo do programa
//Escreve na tela: Ola Mundo.
System.out.println(“Ola Mundo”);
}
}

Pag.: 19
javac OlaMundo.java

java PrimeiraApp

public

static

<NomeCasse>.<NomeMetodoStatic>(argumentos)

void

main

String[] args

Pag.: 20
System.out.println

class AppParametro {
public static void main (String[] args){
System.out.println("Parametros:"+args[0]+""+args[1]+""+
args[2]);

System.out.println("Tamanho terceiro parametro:"+


args[2].length());

System.out.println("Quantidade Parametros:"+args.length);

}
}

java AppParametro Daniela Claro “Menina bonita”

Parametros:Daniela Claro Menina Bonita


Tamanho terceiro parametro:13
Quantidade Parametros:3

Pag.: 21
Fundamentos da Linguagem

/* texto */

// texto

abstract do implements package throw


boolena double impor private throws
break else inner protected transient
byte extends instanceof public try
case final int rest var
cast finally interface return void
catch float long short volatile
char for native static while
class future new super
const generic null switch
continue goto operator syncronized
default if outer this

Pag.: 22
Fundamentos da Linguagem

<tipo> <identificador> [= <valor inicial>];

Pag.: 23
Fundamentos da Linguagem

<identificador> = <valor>;

int diasFerias, outroInteiro;


double salario;
float umFloat = 0.5;
char letra = ‘i’;
boolean achou = false;
diasFerias = 30;

int diasFerias; //Somente a declaração da variável ou atributo


diasFerias = 30; //Inicialização da variável com o valor 30

final double AUMENTO = 5,25;

Pag.: 24
Fundamentos da Linguagem

15/2 = 7
15.0 / 2 = 7,5

x += 10; // Equivale x = x + 10;


x += y; // Equivale x = x + y;
a -= b; // Equivale a = a – b;
a *= 3; // Equivale a = a * 3;

Pag.: 25
Fundamentos da Linguagem

int a = 7;
int b = 7;
int x = 2 * ++a;
int y = 2 * b++;

a=8, b=8, x=16 e y=14

x<y ? e1:e2

String a = 1<2 ? “Menor” : “Menor”

a “Menor ”

Pag.: 26
Fundamentos da Linguagem

Exemplo:
short varshort;
int varInt;

varInt = varShort;
varShort = varInt; //Tipo incompatível para conversão, short é
menor que int

short varshort;
int varInt;

varInt = varShort;
varShort = (short) varInt;

Pag.: 27
Fundamentos da Linguagem

if ( boolean )
declaração1;
else
declaração2;

if (fim == true)
System.out.println(“Término!”);
else
System.out.println(“Continuando...”);

if (fim == true){
cont = 0;
System.out.println(“Término”);
} else {
cont = cont +1;
System.out.println(“Continuando...”);
}

if (x>0)
if (y>=0)
sinal=0;
else
sinal=1;

Pag.: 28
Fundamentos da Linguagem

while (booleano)
declaração;

while ( i != 0 ){
salario = salario * 0.5;
i--;
}

do
declaração
while (booleano);

do {
salario = salario * 0.5;
i--;
} while ( i != 0 );

for (expressao; booleano; expressao)


declaracao;

Pag.: 29
Fundamentos da Linguagem

for (i = 0; i < 20; i ++)


salario = salario * 0.5;

case
switch

switch ( expressão ) {
case valor: declaração;
...
default: declaração;
}

switch ( cmd ){
case 1: System.out.println(“Item do menu 1”);
break;
case 2: System.out.println(“Item do menu 2”);
break;
case 3: System.out.println(“Item do menu 3”);
break;
default: System.out.println(“Comando invalido!”);
}

break

return expressão;

class Teste{
public int Potencia ( int base, int n){
int result = base;
for ( int i = 0; i < n-1; i ++ )

Pag.: 30
Fundamentos da Linguagem

result = result * base;


return result;
}
}

int i = 0;
while (true) {
System.out.println(i);
i++;
if ( i > 10 ) break;
}

for (int i = -10; i<10; i++){


if ( i == 0 )
continue;
System.out.println(1/i);
}

int[] nums = new int [5];

Pag.: 31
Fundamentos da Linguagem

Pag.: 32
Orientação a Objetos em Java

Pag.: 33
Orientação a Objetos em Java

<tipo> <identificador> [= <valor inicial>];

<identificador> = <valor>;

....
int umInteiro, outroInteiro;
float umFloat = 0.5;
char caracter = ‘i’;
boolean achou = false;
umInteiro = 90;
....

public class A{
public static void main (String[] args){
//atributo de tipo primitivo
int a;
a = 1;
System.out.println( +a);

//atributo de tipo objeto


int[] b;
b = new int[3];
b[0] = 10;
b[1] = 20;
b[2] = 30;
for (int i=0; i<3; i++)
System.out.println( +b[i]);
}
}

Pag.: 34
Orientação a Objetos em Java

{
......
declaração de atributos
......
public void Metodo(parametros)

{
......
declaração de variáveis
locais
...

Escopo de
Variáveis
catch(parâmetros){
Locais
.....
.....
}
Escopo de

Pag.: 35
Orientação a Objetos em Java

class Parametro {
public int adicionaDois(int i){
i = i+ 2;
System.out.println("Valor de i " + i );
return i;
}
public static void main (String[] args ){
int i = 11;
System.out.println("Valor inicial de i " + i );

//cria objeto da classe


Parametro oParam = new Parametro();

//método AdicionaDois, resultado é colocado em j


int j = oParam.adicionaDois(i);

//Mostra os valores de i e de j
System.out.println("Valor de j " + j );
System.out.println("Valor final de i " + i );
}
}

public void aumentarSalario(double percentual){


double aumento = salário*percentual/100;
salário += aumento;
}

meuObjeto.aumentoSalario(double percentual)

public void aumentarSalario(double percentual){


double aumento = this.salário*percentual/100;
this.salário += aumento;
}

Pag.: 36
Orientação a Objetos em Java

....
Empresa emp; //objeto não foi criado, então é null
emp.Atualizar ( nome, cgc );
.....

....
if ( emp = = null)
System.out.println("Objeto empresa não foi criado");
else emp.Atualizar ( nome, cgc );
.....

Pag.: 37
Orientação a Objetos em Java

*.java

java.lang.*

Pag.: 38
Orientação a Objetos em Java

Date data;

data

Date data;
data.toString();

new().

Data data = new Data();

...
Empresa emp;
emp = new Empresa( nome, end );
....
ou
...
Empresa emp = new Empresa( nome, end );
....

Pag.: 39
Orientação a Objetos em Java

class Teste {
Pessoa umaPessoa;
Pessoa outraPessoa = new Pessoa ("João");
int inteiro;
int numero = 15;
}

[modificadores]<tipoRetorno><nomeMetodo>([<tipoParamN>
<ident.ParamN>, .... ] ) [throws <ClasseThrowableN>,....];

class Exemplo{
private float salario;

//outros métodos

public String retorneSalario( ){


return salario;
}
}

Pag.: 40
Orientação a Objetos em Java

class Inteiro {
static int ValorMax = 100000;
}

class Empregado {
private int id;
private static int nextid;
}

public void setId(){


id(pedro) id(daniela) nextId
id=nextid;
nextId++; 0 0 1
} 1 1 2
pedro.setId(); 3
daniela.setId();

1
Este exemplo, como muitos outros presentes neste livro, foi adaptado do livro Core Java 2 (CORNELL, 2002), por ser considerado, por
mim(Daniela), um dos melhores livros de Java que ja utilizei. Inclusive adotado nas Universidades onde lecionei, por ser didatico e muito
explicativo.

Pag.: 41
Orientação a Objetos em Java

class Exemplo{
static void ImprimeMsg( ){
System.out.println("Requisição inválida!");
}
}

public static int getNextId(){


nextId++;
}

class Teste{
finalize ( ){
//tarefas a serem encerradas
}
}

class Empresa{
String nome;
String endereço,

Pag.: 42
Orientação a Objetos em Java

Empresa ( ){
nome = "não definido";
endereço = "vazio";
}

Empresa ( String nm_empresa, String end_empresa ){


nome = nm_empresa;
endereço = end_empresa;
}
}

class Parametro{
static int AdicionaQuatro( int i) {
i = i + 4;
System.out.println("Valor da cópia local: " + i );
Return i;
}
static static void main( String S[ ] ) {
System.out.println("Passagem de parâmetros! " );
int i = 10;
System.out.println("Valor original de i: " + i );
int j = AdicionaQuatro(i);
System.out.println("Valor de j: " + j );
System.out.println("Valor corrente de i: " + i );
}
}

Valor original de i: 10
Valor da cópia local: 14
Valor de j: 14
Valor corrente de i: 10

Pag.: 43
Orientação a Objetos em Java

public class ParametroReferencia{


static void MudaArray ( int[] variavel ) {
variavel[2] = 100;
}
public static void main( String[] S ) {
int umArray[] = new int [3];
umArray[2] = 10;
System.out.println("umArray[2] antes = " + umArray[2]);
MudaArray( umArray );
System.out.println("umArray[2] depois = " +
umArray[2]);
}
}

umArray[2] antes = 10
umArray[2] depois = 100

class Gerente extends Empregado

class Gerente extends Empregado{


private double bônus;
public void setBonus(double d){

Pag.: 44
Orientação a Objetos em Java

bonus=b;
}
}

Gerente chefe = new Gerente();


chefe.setBonus(500);

getNome() getCidade()

getSalario()

getSalario()

class Empregado {
priavate String nome;
priavate double salario;

public String getSalario(){


return this.salario;
}
}

class Gerente extends Empregado{


private double bônus;
public double getSalario(){
return salario + bonus;
}
}

public class Carro{


public void LavaCarro( ){
//comandos para lavar o carro
}
}
public class Gol extends Carro{
public void LavaCarro( ){
super.LavaCarro( );//Acessa método da classe Carro
}
}

Pag.: 45
Orientação a Objetos em Java

public class Carro{


String carro, sabao, local;
public Carro( String nome){ //Método construtor
carro = nome;
sabao = "marca";
local = "lavajato";
}
}
public class Gol extends Carro{
public Gol ( ){
super ( "gol" ); //Acessa construtor da classe Carro
}
}

Classe Object

Classe Pai Classe Outra

Classe Filho Classe Filha

Classe Neta

class Pai {
.......
}
class Filho extends Pai {
.......
}
class Filha extends Pai {
.......
}
class Neta extends Filha {

Pag.: 46
Orientação a Objetos em Java

.......
}

Gerente chefe = new Gerente(“Daniela”,8000);


chefe.setBonus(500);

Empregado emp = new Empregado[3];//Array de empregados

emp[0] = chefe;
emp[1] = new Empregado(“Pedro”,5000);
emp[3] = new Empregado(“João”,3000);

Empregado

Gerente

for(int i..){
Empregado e = emp[i];
System.out.println(e.getNome + e.getSalario());
}

Pag.: 47
Orientação a Objetos em Java

final class Gol extends Carro{ }


//Evita que criem subclasses da classe Gol

public final void lavaCarro(){


...
}//Esse metodo nao pode existir em nenhuma outra classe filha.

final String TESTE= “teste”;

Pag.: 48
Orientação a Objetos em Java

Instituição

Universidade Escola Superior

public abstract String getNome();


public abstract String getEndereco();

Instituicao ins = new Universidade();

Pag.: 49
Orientação a Objetos em Java

double a= 3,4567;
int novoA= (int)a;

Empregado

Gerente

Gerente chefe = (Gerente) empregado[1];

instanceOf

f(emp[1] instanceOf Gerente){


chefe = (Gerente)emp[1];
...
}

Instituição c = (Instituição)emp[1];

Pag.: 50
Orientação a Objetos em Java

public interface Festa{


void fazBolo(int tamanho);
}

public interface Festa {


void fazBolo(int tamanho);
boolean encherBolas(int quantidade);
int convidarPessoa(String nome);
}

class Aniversario implements Festa {


...
}

Pag.: 51
Tratamento de Exceção

try{
...
}catch(Tipo da Exceção) {
...
}

class ExcecaoBasico{
public static void main(String[] args){
try {
int a = 2/0;
}catch (Exception e ){
System.err.println("Aconteceu um problema:"+e);
}
}
}

Pag.: 52
Tratamento de Exceção

try{
System.out.println("Tentando executar o codigo.");
}catch (Exception e){
System.err.println("Excecao capturada:"+e);
}finally{
System.err.println("Finally executado!");
}

try {
a = Integer.valueOf(numero1.getText()).intValue();
b = Integer.valueOf(numero2.getText()).intValue();
resultado = a / b;
if (b < 0)
throw new Exception();
Message.texto("Este é o resultado:"+ resultado);
Message.setVisible(true);
}catch (ArithmeticException e){
Message.texto("Gerou uma exceção Aritmetica - Divisão por zero");
Message.setVisible(true);
}catch (NumberFormatException e){
Message.texto("Gerou uma exceção no Numero da divisão");
Message.setVisible(true);
}catch (Exception e){
Message.texto("Gerou uma exceção Geral:"+e);
Message.setVisible(true);
}finally {
MessageBox msgGeral = new MessageBox();
msgGeral.texto("Um resultado, ou uma exceção, o programa está
funcionando!!!");
msgGeral.setVisible(true);
}

throw

import java.awt.*;
import java.awt.event.*;
import MessageBox;

class GeraExcecao extends Frame implements ActionListener{


int resultado;
int a;
int b;
MessageBox Message;
TextField numero1;
TextField numero2;
Button btnOk;

GeraExcecao (){
setLayout (null);
setSize(400,400);

Message= new MessageBox();

numero1 = new TextField();


numero1.setBounds(60,40,80,30);
add(numero1);

Pag.: 53
Tratamento de Exceção

numero2 = new TextField();


numero2.setBounds(60,100,80,30);
add(numero2);

btnOk = new Button("Execute!!");


btnOk.setBounds(160,100,70,30);
add(btnOk);

btnOk.addActionListener(this);
}

public void teste(){


try {
a = Integer.valueOf(numero1.getText()).intValue();
b = Integer.valueOf(numero2.getText()).intValue();
resultado = a / b;
if (b < 0)
throw new Exception();
Message.texto("Este é o resultado:"+ resultado);
Message.setVisible(true);
} catch (ArithmeticException e){
Message.texto("Gerou uma exceção Aritmetica - Divisão por zero");
Message.setVisible(true);
}catch (NumberFormatException e){
Message.texto("Gerou uma exceção no Numero da divisão");
Message.setVisible(true);

}catch (Exception e){


Message.texto("Gerou uma exceção Geral:"+ e);
Message.setVisible(true);
}
}

public void actionPerformed(ActionEvent e){


if (e.getSource() == btnOk){
teste();
}
}

public static void main (String args[]){


GeraExcecao form = new GeraExcecao();
form.setVisible(true);

}
}//Fechamento da classe

class DivisaoPorZero extends ArithmeticException{


DivisaoPorZero(){

Pag.: 54
Tratamento de Exceção

super("Foi gerada uma excecao devido a Divisao por zero");


}
DivisaoPorZero(String msg){
super(msg);
}
}
public class Excecao2{
public static void main(String[] args) throws DivisaoPorZero {
try {
int a=0, b = 0;
if (b!=0){
a = a/b;
}else{
throw new DivisaoPorZero();
}
}catch (DivisaoPorZero e ){
System.err.println("Aconteceu um problema:"+e);
System.err.println("PrintMessage:"+e.getMessage());
e.printStackTrace();
}catch (Exception f ){
System.err.println("Capturou excecao normal:"+f);
}
}
}

Throwable

Error Exception

I/O Exception RuntimeException

Pag.: 55
Interface Gráfica - AWT

Pag.: 56
Interface Gráfica - AWT

Pag.: 57
Interface Gráfica - AWT

Pag.: 58
Interface Gráfica - AWT

Pag.: 59
Interface Gráfica - AWT

Pag.: 60
Interface Gráfica - AWT

Pag.: 61
Interface Gráfica - AWT

Pag.: 62
Interface Gráfica - AWT

Pag.: 63
Applets

Pag.: 64
Applets

class PrimeiraInterface extends JFrame{


public PrimeiraInterface(){
setSize(300,200);
}
public static void main(String[] args){
PrimeiraInterface frame = new PrimeiraInterface();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

Container contentPane = frame.getContentPane();


frame.setContentPane(c);

Pag.: 65
Applets

frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

Pag.: 66
Applets

Pag.: 67
Applets

Pag.: 68
Applets

...
public void init()
{
...
param1 = getParameter(“NomeParam1”);
param2 = getParameter(“NomeParam2”);
...
}
...

import java.applet.*;
import java.awt.*;

public class ParamApplet extends Applet{


String codigo;
public void init(){
codigo=getParameter("codigo");
}

public void paint(Graphics g){


g.drawString("Codigo: "+codigo ,20,20);
}
}

<HTML>
<BODY background="#000000">
<APPLET CODE=ParamApplet.class WIDTH=300 HEIGHT=100>
<PARAM NAME="codigo" VALUE="55010">
</APPLET>
</BODY>
</HTML>

Pag.: 69
Applets

Font f = new Font (<nomeFonte>, <estilo>, <tamanho>);

public void paint(Graphics g){


g.setFont(new Font(“Symbol”, Font.BOLD, 14));
}

Pag.: 70
Applets

Color c1 = Color.white;
Color c2 = new Color(255, 0, 0);
Color c3 = new Color( 0.0f, 1.0f, 0.0f );

public void paint(Graphics g ){


g.setColor(Color.red);
}

Pag.: 71
Processamento Concorrente - Threads

public class PrimeiraThread extends Thread {

public void run(){


....
}

PrimeiraThread pt = new PrimeiraThread()


pt.start();//executa o método run()

lass X extends Thread

class X extends JFrame implements Runnable

Pag.: 72
Processamento Concorrente - Threads

import java.applet.Applet;
import java.awt.*;
import java.awt.Graphics;
import java.util.*;
import java.text.DateFormat;
import java.awt.event.*;
import MessageBox;

public class Thread1 extends Applet implements ActionListener,


Runnable{
Button btnOk;
TextField edNome;
Label lbTitulo;
Label lbMensagem;
Panel pnSaida;
MessageBox mensagem;

Thread appClock;

public void init(){


setLayout(null);
setSize(400,300);
setBackground(Color.gray);

pnSaida = new Panel();


pnSaida.setBounds(20,20,330,40);
pnSaida.setBackground(Color.yellow);
add(pnSaida);

lbTitulo = new Label("Gerador de Mensagens");


lbTitulo.setBounds(170,25,200,40);
pnSaida.add(lbTitulo);

lbMensagem = new Label("Mensagem:");


lbMensagem.setBounds(20,80,80,30);
add(lbMensagem);

Pag.: 73
Processamento Concorrente - Threads

edNome = new TextField("Daniela Claro");


edNome.setBounds(20,110,200,24);
add(edNome);

btnOk = new Button("Mostra Mensagem!");


btnOk.setBounds(250,90,120,40);
add(btnOk);

btnOk.addActionListener(this);
}
public void start(){
appClock = new Thread(this, "Clock");
appClock.start();
}
public void run(){
while (appClock == Thread.currentThread()) {
repaint();
}
}
public void paint(Graphics g){
Calendar cal = Calendar.getInstance();
Date data = cal.getTime();
DateFormat dateFormatter = DateFormat.getTimeInstance();
g.drawString(dateFormatter.format(data),5,10);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == btnOk){
mensagem = new MessageBox(edNome.getText());
mensagem.setVisible(true);
showStatus(edNome.getText());
}
}
}

public class Sequencia implements Runnable{


public void run(){
while(true){
System.out.println(Thread.currentThread().getName());
}
}
public static void main (String args[]){
Sequencia form = new Sequencia();
new Thread(form, "Primeira Sequencia").start();
new Thread(form, "Segunda Sequencia").start();
}
}

Pag.: 74
Processamento Concorrente - Threads

public void run(){


while(true){
System.out.println(Thread.currentThread().getName());
Thread.yield();
}
}

public class ContadorSeguro {


int ValorCrucial;
public synchronized void contar(){
ValorCrucial += 1;
}
}

Pag.: 75
Processamento Concorrente - Threads

Pag.: 76
Sockets

Cliente 1

Servidor
Cliente 2

Cliente 3

Conexão virtual

Pag.: 77
Sockets

import java.net.*;
import java.io.*;

public class Servidor{


public static void main(String[] args) throws IOException{

ServerSocket serverSocket = null;


try {
serverSocket = new ServerSocket(4445);
}catch (IOException e){
System.err.println("O servidor nao pode ouvir a porta");
System.exit(1);
}

Socket clientSocket = null;


try {
System.out.println("Servidor esperando conexão!");
clientSocket = serverSocket.accept();
}catch (IOException e){
System.err.println("A conexao falhou!");
System.exit(1);
}

PrintWriter out = new PrintWriter ( clientSocket.getOutputStream(),true);


BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
out.println(in.readLine());
}
}

Pag.: 78
Sockets

import java.io.*;
import java.net.*;

public class EchoClient {

public static void main(String[] args) throws IOException {


Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;

try {
echoSocket = new Socket("127.0.0.1", 4445);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Host desconhecido");
System.exit(1);
} catch (IOException e) {
System.err.println("Nao foi possivel estabeler uma conexao.");
System.exit(1);
}

for(int vc=0; vc<args.length; vc++) {


out.println(args[vc]);
System.out.println("echo: " + in.readLine());
}

out.close();
in.close();
echoSocket.close();
}
}

Pag.: 79
Acesso a Banco de Dados - JDBC

Pag.: 80
Acesso a Banco de Dados - JDBC

Pag.: 81
Acesso a Banco de Dados - JDBC

Pag.: 82
Acesso a Banco de Dados - JDBC

jdbc:<subprotocolo>:<subname>

jdbc:odbc:JdbcOdbcDriver

Pag.: 83
Acesso a Banco de Dados - JDBC

jdbc:odbc:cursoJDBC,””,””

jdbc:mysql://localhost/JAVADB

Connection con = DriverManager.getConnection(url, userid, passwd);

import java.SQL.*;

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:JavafichaDB", "", "");
}
catch (Exception e){
System.out.println(e.toString());
System.exit(0);
}

con.close();

Pag.: 84
Acesso a Banco de Dados - JDBC

Statement stmt = con.createStatement();


stmt.executeQuery(“SELECT * FROM curso”);
stmt.executeUpdate(“DELETE FROM curso WHERE cpf=3333”);

ResultSet rs = stmt.executeQuery("SELECT * FROM curso");


rs.getString(“nome”);
rs.getString(2);

Pag.: 85
Acesso a Banco de Dados - JDBC

stmt = con.prepareStatement(“UPDATE pessoa SET nome=?”);

pstmt.setString(1,”Bosco”);
pstmt.executeUpdate();

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);

if (ae.getSource()== btnConsulta){
System.out.println("Realizando uma consulta...");
stmt= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(MetodoSQL.mConsultar());
if (rs.last()){
int nQtde = rs.getRow();
lbQuantidade.setText("Quantidade: "+nQtde);
rs.beforeFirst();
}
if (rs.next()){
edCPF.setText(rs.getString("CPF"));
edNome.setText(rs.getString("nome"));
edCidade.setText(rs.getString("cidade"));
}
}

Pag.: 86
Acesso a Banco de Dados - JDBC

stmt.executeUpdate(“UPDATE curso SET nome=’Daniela’”);

if (edCPF.getText().trim().equals("")|| edNome.getText().trim().equals("")||
edCidade.getText().trim().equals("")){
System.out.println("Os campos devem estar preenchidos");
} else {
System.out.println("Campos OK - Realizar a inserção");
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
uprs = stmt.executeQuery("SELECT cpf,nome,cidade FROM PESSOA");
uprs.moveToInsertRow();
uprs.updateString("cpf",edCPF.getText());
uprs.updateString("nome", edNome.getText());
uprs.updateString("cidade", edCidade.getText());
uprs.insertRow();
}

CREATE TABLE Usuario OF objUsuario (UsuarioID PRIMARY KEY);

SELECT Emp.UsuarioID.Nome as Nome, Emp.LivroID.Titulo as Titulo


FROM Emprestimo Emp;

Pag.: 87
Referências Bibliográficas

Pag.: 88
Referências Bibliográficas

Pag.: 89

Você também pode gostar