INTRODUÇÃO À LINGUAGEM DE
PROGRAMAÇÃO
PLATAFORMA JAVA
Roda em diferentes Sistemas Operacionais.
JMV (Java Virtual Machine).
J2SE – Aplicações desktop.
J2EE – Especificação para aplicações multicamadas –
Web.
PREPANDO O AMBIENTE
Download JDK (JAVA Developer Kit)
http://www.sun.com
Download Eclipse (IDE para desenvolvimento)
http://www.eclipse.org
Download MySQL
http://www.mysql.com
mysql-gui-tools-5.0-r10-win32.msi
mysql-5.0.37-win32.zip
mysql-connector-java-5.0.5.zip
C:\Program Files\Java\jdk1.6.0\jre\lib\ext
PRIMEIRO EXEMPLO
public class Exemplo1 {
public static void main(String[] args) {
String mensagem = "Primeiro Exemplo em JAVA";
System.out.println(mensagem);
}
}
TIPOS DE VARIÁVEIS
5
public class Variaveis {
public static void main(String[] args) {
int inteiro = 50;
double ponto = 1.098123;
String texto = "Texto";
char caracter = 'c';
boolean tf = true;
// Este é um comentario por linha
/*
* Este é um Comentario
* Por bloco
*/
System.out.println("Variavel inteira: " + inteiro);
System.out.println("Variavel com ponto: " + ponto);
System.out.println("Variavel String: " + texto);
System.out.println("Variavel caracter: " + caracter);
System.out.println("Variavel booleana: " + tf);
}
}
CONVENÇÕES SORE NOME DE
VARIÁVEIS
O nome da variável deve começar com letra minúscula e
nomes de classes devem começar com letras maiúsculas.
Se o nome da variável contiver mais de uma palavra, a
primeira letra de cada palavra subsequente deve iniciar
em maiúscula.
O underscore ( _ ) deve ser utilizado apenas para separar
palavras em constates.
Não podemos utilizar palavras chaves como nome de
PALAVRAS CHAVES
abstract
continue
for
switch
assert
default
goto
package
booleando
if
private
new
break
double
implements
protected
byte
else
import
public
case
enum
instanceof
return
catch
extends int
short
try
char
final
interface
static
class
finally
long
strictfp
const
float
native
super
while
volatile
void
transient
ESCOPO DA VARIÁVEL
Região, dentro do programa, onde a variável pode ser referenciada,
simplesmente pelo nome.
public class Escopo {
static String global = "Variavel global";
public static void main(String[] args) {
int num1 = 20;
for (int i = 0; i<=2; i++){
System.out.println("Interacao:" + i);
}
System.out.println(global);
System.out.println(num1);
// System.out.println(i);
}
VARIÁVEL FINAL
CONSTANTE
Após inicializada, seu valor não poderá mais ser alterado.
public class Final {
public static void main(String[] args) {
final int I = 10;
final int J = 5;
// I = 5;
// J = 2;
System.out.println("Soma: " + (I + J));
}
}
9
OPERADORES
public class Operadores {
public static void main(String[] args) {
int i = 1;
System.out.println("i: " + i);
i = i + 2;
System.out.println("i + 2: " + i);
i += 3;
System.out.println("i += 3: " + i);
i -= 2;
System.out.println("i -= 2: " + i);
}
}
OPERADORES
public class Operadores {
public static void main(String[] args) {
int i = 4;
int j = 2;
System.out.println("i + j: " + (i + j));
System.out.println("i - j: " + (i - j));
System.out.println("i * j: " + (i * j));
System.out.println("i / j: " + (i / j));
System.out.println("i % j: " + (i % j));
}
}
11
PRÉ E PÓS INCREMENTOS
public class Operadores {
public static void main(String[] args) {
i = 2;
System.out.println("i: " + i);
System.out.println("i++: " + i++);
System.out.println("i: " + i);
System.out.println("++i: " + ++i);
}
}
CONTROLE DE FLUXO - WHILE
public class Fluxo {
public static void main(String[] args) {
int i = 0;
while (i <= 5){
System.out.println("Valor de i: " + i);
i++;
}
}
}
13
CONTROLE DE FLUXO – DO...WHILE
public class Fluxo {
public static void main(String[] args) {
int i = 0;
do{
System.out.println("Valor de i: " + i);
i++;
} while (i <= 5);
}
}
CONTROLE DE FLUXO - FOR
public class Fluxo {
public static void main(String[] args) {
for (int a = 0; a <= 5; a++){
System.out.println("Valor de a: " + a);
}
}
}
CONTROLE DE FLUXO – FOR
public class Fluxo {
public static void main(String[] args) {
int i = 1;
for (;;) { // loop infinito
System.out.println("Valor de a: " + a);
if (i == 6){
break;
}
}
}
}
CONTROLE DE FLUXO - IF
public class Fluxo {
public static void main(String[] args) {
double nota = 7.0;
if (nota >= 5.0){
System.out.println("Aprovado!");
}
if (nota < 5.0){
System.out.println("Reprovado!");
}
}
}
17
CONTROLE DE FLUXO - IF
public class Fluxo {
public static void main(String[] args) {
double nota = 7.0;
if (nota >= 5.0){
System.out.println("Aprovado!");
}
else{
System.out.println("Reprovado!");
}
}
}
CONTROLE DE FLUXO - IF
public class Fluxo {
public static void main(String[] args) {
double nota = 4.8;
System.out.println((nota >= 5.0) ? "Aprovado!"
: "Reprovado!");
}
}
19
CONTROLE DE FLUXO - IF
public class Fluxo {
public static void main(String[] args) {
double teste = 1.2;
char conceito;
if (teste >= 9.0){
conceito = 'A';
}else if (teste >= 7.5){
conceito = 'B';
}else if (teste >= 5.0){
conceito = 'C';
}else{
conceito = 'D';
}
System.out.println("Conceito: " + conceito);
}
CONTROLE DE FLUXO - SWITCH
public class Fluxo {public static void main(String[] args) { int semana = 3; switch(semana){ case 1: System.out.println("Domingo"); break; case 2: System.out.println("Segunda"); break; case 3: System.out.println("Terça"); break; … default: System.out.println("Dia Inválido"); break; } } }
21
CLASSE SWING
import javax.swing.*;
public class Swing {
public static void main(String[] args) {
String tmp = "";
double a = 0, b = 0;;
tmp = JOptionPane.showInputDialog("Entre com um numero: ");
try{
a = Double.parseDouble(tmp);
} catch (Exception e){
System.out.println("Informe somente numeros!");
System.exit(0);
CLASSE SWING
tmp = JOptionPane.showInputDialog("Entre com outro
numero: ");
try{
b = Double.parseDouble(tmp);
}catch(Exception e){
System.out.println("Informe somente numeros!");
System.exit(0);
}
JOptionPane.showMessageDialog(null, "A soma
é igual a: " + (a+b), "Resultado",
JOptionPane.INFORMATION_MESSAGE);
}
VETORES / ARRAYS
import java.util.Arrays;
public class Vetor2 {
public static void main(String[] args) {
String nomes[];
nomes = new String[5];
nomes[0] = "Tulio";
nomes[1] = "Jose";
nomes[2] = "Maria";
nomes[3] = "Joana";
nomes[4] = "Joaquina";
VETORES / ARRAYS
for (int i = 0; i<nomes.length; i++){
System.out.println("Posicao[" + i + "]: " + nomes[i]);
}
Arrays.sort(nomes);
System.out.println("Nomes Ordenados: ");
for (int i = 0; i<nomes.length; i++){
System.out.println("Posicao[" + i + "]: " + nomes[i]);
}
}
}
VETORES / ARRAYS
public class Vetor {
final int TAMANHO = 20;
int numeros[ ] = new int[ TAMANHO ];
public int tamanho(){
return numeros.length;
}
public void insereElementos(){
int i = 0;
while(i < numeros.length){
numeros[i] = (int) (Math.random() * 10);
i++;
VETORES / ARRAYS
public void mostraElementos(){
for (int i = 0; i< numeros.length; i++)
System.out.println("Posicao[ " + i + "]: " + numeros[i]);
}
}
VETORES / ARRAYS
public class TestaVetor {
public static void main(String[] args) {
Vetor a = new Vetor();
a.insereElementos();
a.mostraElementos();
System.out.println("O tamanho do vetor é: " + a.tamanho());
}
MATRIZES / VETORES
MULTIDIMENSIONAIS
public class Matriz {
final int LINHA = 3;
final int COLUNA = 3;
int matriz[ ][ ] = new int [LINHA][COLUNA];
public void insereElementos(){
for(int i = 0; i<LINHA; i++)
for(int j = 0; j<COLUNA; j++)
matriz[ i ][ j ] = (int) (Math.random() * 10);
}
MATRIZES / VETORES
MULTIDIMENSIONAIS
public void exibeElementos(){
for (int i = 0; i<LINHA; i++)
for (int j = 0; j<COLUNA; j++)
System.out.println("Posicao[ " + i + " ][ " + j + " ]: "
+ matriz[i][j]);
}
public void removeElemento(int linha, int coluna){
matriz[linha][coluna] = 0;
}
public void diagonalPrincipal(){
for(int i = 0; i<LINHA; i++)
MATRIZES / VETORES
MULTIDIMENSIONAIS
System.out.println("Posicao[ " + i + " ][ " + j + " ]: " + matriz[i][j]);
}
}
}
public void diagonalSecundaria(){
for(int i = 0; i<LINHA; i++)
for(int j = 0; j<COLUNA; j++){
if ((i + j) == (LINHA - 1)){
System.out.println("Posicao[ " + i + " ][ "
+ j + " ]: " + matriz[i][j]);
}
}
}
31
MATRIZES / VETORES
MULTIDIMENSIONAIS
public int determinante (){
int dp = 1, ds = 1;
for (int i = 0; i<LINHA; i++)
for (int j = 0; j<COLUNA; j++){
if (i == j){
dp = dp * matriz[i][j];
}
if ((i + j) == (LINHA - 1)){
ds = ds * matriz[i][j];
}
}
return dp - ds;
}
MATRIZES / VETORES
MULTIDIMENSIONAIS
public class TestaMatriz {
public static void main(String[] args) {
Matriz m = new Matriz();
m.insereElementos();
m.exibeElementos();
System.out.println("Diagonal Principal: ");
m.diagonalPrincipal();
System.out.println("Diagonal Secundaria: ");
m.diagonalSecundaria();
System.out.println("Determinante: " + m.determinante());
}
}
33
INTRODUÇÃO A ORIENTAÇÃO A OBJETOS
(OO)
Carro
cor
modelo
ano
fabricante
setCor
setModelo
getFabricante
getAno
getCor
Atributos
Métodos
Classe
Objetos
Herança
Polimorfismo
Instância
EXERCÍCIO
Criar uma classe Pessoa com os seguintes atributos:
Nome
Idade
Sexo
E com os seguintes métodos:
Atribuir valores para todos os atributos
Retornar os valores de todos os atributos
Retornar a % de mulhers com idade entre 20 e 40 anos
Retonar o N de homens com menos de 30 anos
EXERCÍCIO - CONTINUAÇÃO
Criar uma classe chamada TestePessoa
Criar 5 objetos do tipo Pessoa
Atribuir valores a todos os atributos
Retornar todos os valores
Retornar a % de mulhers com idade entre 20 e 40 anos
FORMULÁRIOS
public class Formularios implements ActionListener { JFrame f = new JFrame();
JPanel jp = new JPanel();
JTextField display = new JTextField(); JButton um = new JButton("1"); JButton dois = new JButton("2"); JButton tres = new JButton("3"); JButton quatro = new JButton("4"); JButton cinco = new JButton("5"); JButton seis = new JButton("6"); JButton sete = new JButton("7"); JButton oito = new JButton("8"); JButton nove = new JButton("9"); JButton limpa = new JButton("C"); JButton zero = new JButton("0"); JButton igual = new JButton("="); JButton menos = new JButton("-"); JButton mais = new JButton("+"); JButton dividir = new JButton("/");
FORMULÁRIOS
String op = "";
int var1 = 0, var2 = 0, resultado = 0;
public void criaTela(){
f.setSize(230, 400);
f.setLocation(800, 80);
f.setTitle("Calculadora");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp.setLayout(null);
display.setBounds(11, 10, 200, 20);
display.setEditable(false);
jp.add(display);
um.setBounds(11, 60, 50, 20);
jp.add(um);
FORMULÁRIOS
dois.setBounds(86, 60, 50, 20); jp.add(dois); dois.addActionListener(this); tres.setBounds(160, 60, 50, 20); jp.add(tres); tres.addActionListener(this); quatro.setBounds(11, 100, 50, 20); jp.add(quatro); quatro.addActionListener(this); cinco.setBounds(86, 100, 50, 20); jp.add(cinco); cinco.addActionListener(this); seis.setBounds(160, 100, 50, 20); jp.add(seis); seis.addActionListener(this);39
FORMULÁRIOS
sete.setBounds(11, 140, 50, 20); jp.add(sete); sete.addActionListener(this); oito.setBounds(86, 140, 50, 20); jp.add(oito); oito.addActionListener(this); nove.setBounds(160, 140, 50, 20); jp.add(nove); nove.addActionListener(this); limpa.setBounds(11, 180, 50, 20); jp.add(limpa); limpa.addActionListener(this); zero.setBounds(86, 180, 50, 20); jp.add(zero); zero.addActionListener(this);FORMULÁRIOS
igual.setBounds(160, 180, 50, 20); jp.add(igual); igual.addActionListener(this); menos.setBounds(30, 250, 60, 30); jp.add(menos); menos.addActionListener(this); mais.setBounds(130, 250, 60, 30); jp.add(mais); mais.addActionListener(this); dividir.setBounds(30, 310, 60, 30); jp.add(dividir); dividir.addActionListener(this); vezes.setBounds(130, 310, 60, 30); jp.add(vezes); vezes.addActionListener(this);41
FORMULÁRIOS
f.add(jp);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Object o = e.getSource();
if(o == um){
display.setText(display.getText() + 1);
}
if(o == dois){
display.setText(display.getText() + 2);
}
if(o == tres){
display.setText(display.getText() + 3);
FORMULÁRIOS
if(o == quatro){
display.setText(display.getText() + 4);
}
if(o == cinco){
display.setText(display.getText() + 5);
}
if(o == seis){
display.setText(display.getText() + 6);
}
if(o == sete){
display.setText(display.getText() + 7);
}
if(o == oito){
display.setText(display.getText() + 8);
}
43
FORMULÁRIOS
if(o == nove){
display.setText(display.getText() + 9);
}
if(o == zero){
display.setText(display.getText() + 0);
}
if(o == limpa){
display.setText("");
}
if(o == mais){
var1 = Integer.parseInt(display.getText());
display.setText("");
op = "+";
FORMULÁRIOS
if(o == menos){
var1 = Integer.parseInt(display.getText());
display.setText("");
op = "-";
}
if(o == vezes){
var1 = Integer.parseInt(display.getText());
display.setText("");
op = "*";
}
if(o == dividir){
var1 = Integer.parseInt(display.getText());
display.setText("");
op = "/";
}
45
FORMULÁRIOS
if(o == igual){
var2 = Integer.parseInt(display.getText());
display.setText("");
if (op == "+"){
resultado = var1 + var2;
}
if (op == "-"){
resultado = var1 - var2;
}
if (op == "*"){
FORMULÁRIOS
if (op == "/"){
resultado = var1 / var2;
}
display.setText(Integer.toString(resultado));
}
}
}
47
FORMULÁRIOS
public class TestaFormulario {
public static void main(String[] args) {
Formularios form = new Formularios();
form.criaTela();
}
}
ACESSO A BANCO DE DADOS - MYSQL
import java.sql.*; public class Banco {
public static String status = "";
public static Connection getConnection(){ Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/loja?user=root&password=123"; con = DriverManager.getConnection(url);
status = "Conexao Aberta!"; }catch(SQLException e){ status = e.getMessage(); }catch(ClassNotFoundException e){ status = e.getMessage(); }catch(Exception e){ status = e.getMessage(); } return con; } }