0% encontró este documento útil (0 votos)
16 vistas6 páginas

Ejemplos de Códigos en Java

El documento presenta conceptos básicos de programación en Java como: 1) mostrar mensajes en pantalla utilizando System.out.println y JOptionPane; 2) declarar y utilizar variables de diferentes tipos primitivos y no primitivos; y 3) crear clases y objetos para representar entidades del mundo real como un coche. Adicionalmente, explica cómo ingresar y mostrar datos utilizando la clase Scanner y realizar cálculos matemáticos con la clase Math.
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
16 vistas6 páginas

Ejemplos de Códigos en Java

El documento presenta conceptos básicos de programación en Java como: 1) mostrar mensajes en pantalla utilizando System.out.println y JOptionPane; 2) declarar y utilizar variables de diferentes tipos primitivos y no primitivos; y 3) crear clases y objetos para representar entidades del mundo real como un coche. Adicionalmente, explica cómo ingresar y mostrar datos utilizando la clase Scanner y realizar cálculos matemáticos con la clase Math.
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd

MOSTRAR EN PANTALLA “HOLA MUNDO”

Import [Link]; //panel de salida y pedida de datos

public class HolaMundo () {


public static main(String[] args) {
[Link](“String”);
}
MOSTRAR EN PANTALLA JOptionPane
import [Link];
public class Introduccion(){
public static void main(String[] args){
String cadena;
int entero;
char letra;
double decimal;
cadena = [Link](“Digite una cadena: “);
entero = [Link]([Link](“Digite un numero
entero: “);
decimal= [Link]([Link](“Digite un numero
flotante: “);
letra = [Link](“Digite un carácter: “).charAt(0);

[Link](null, “La cadena es: “ + cadena);


[Link](null, “El numero entero es: “ + entero);
[Link](null, “El carácter es: “ + letra);
[Link](null, “El decimal es: “+ decimal);
}
}
TIPOS DE DATOS PRIMITIVOS
byte : dato de tipo entero de 8 bits
int : dato de tipo entero de 32 bits
long: dato de tipo entero de 64 bits
short: dato de tipo entero de 16 bits

float: dato de tipo flotante que ocupa 32 bits


float num = (float) 3.45 O float num = 3.45f
double: dato de tipo flotante que ocupa 64 bits
double num = 2.434;

char: dato de tipo carácter de 1 sola variable


char nombre = ‘a’

boolean: dato de tipo binario es decir existen 2 valores, false o true, 0 o 1.

TIPO DE DATOS NO PRIMITIVOS


LOS DATOS NO PRIMITIVOS TE ALMACENAN METODOS

null: el pedazo de memoria esta vacia o no almacena nada.


Integer: almacena valores enteros y permite almacenar el valor null;
String: almacena una frase;
CONSTANTE
final int numero = 10; el numero será igual a 10 siempre:
final char letra = ‘a’ ; la letra será igual siempre;

ENTRADA Y SALIDA DE DATO


PARA DATOS NUMERICOS
package Introduccion;
import [Link]; // NOS PERMITE LA ENTRADA Y SALIDA DE DATOS
public class Introduccion (){
public static void main( String[] args){
Scanner entrada = new Scanner([Link]) ;
int numero;
[Link](“Escriba un numero entero: “):
numero = [Link]();
float real;
[Link](“Escriba un numero real: “);
real = [Link]();
double real11;
[Link](“Escriba un numero real: “);
real11 = [Link]();
OPERADOR DE INCREMENTO Y DECREMENTO
import [Link];
public class Inttr(){
public static void main(String[] args){
int x=5,z=5, j,k;
j=x++;
k=++z;
[Link](“El numero j es: “ + j); //En pantalla sale 5
[Link](“El numero k es: “ + k); // En pantalla sale 6

CLASE MATH
import [Link];
public class Introduccion(){
public static void main( String[] args){
double base,exponente,raíz;
double num = [Link](9) ; //Raiz cuadrada de 9
int num1= (int) [Link](16); //Raiz cuadrada de 16, es necesario el (int)
double num2 = [Link](base, exponente);

float resultado = 4.56f;


int num3 = [Link](resultado); //Nos mostrara en pantalla 5;
float result = 4.58;
int num4 = [Link](result); //Nos muestra en pantalla 4

double num = [Link](); //Nos entrega un numero ramdon;

EJERCICIO 1: PEDIR LA SUMA DE 3 NOTAS


import [Link];
public class Introd(){
public static void main( String[] args){
Scanner entrada = new Scanner([Link]);
float nota1, nota2,nota3;
[Link](“Digite las 3 notas: “);
nota1=[Link]();
nota2=[Link]();
nota3=[Link]();
float suma= nota1+nota2+nota3;
[Link](“\nLa suma es: “+suma);
ARREGLOS UNIDIMENSIONALES
int[] numero= new int[b] ; // b es la cantidad de elementos del arreglo
long[] edad = new long[a]; // a es la cantidad de elementos del arreglo
float[] ………
double[]……..
boolean[]……..
char[]…….
String[]……… // lo mismo para todo lo demás

import [Link];
import [Link];
public class Introduccion(){
public static void main(){
int[] numero = new int[5];
int suma;
for( int i=0; i<5; i++){
numero[i] = [Link]([Link](“Escriba el numero ”
+ (i+1) );
suma = suma + numero[i];
}
[Link](“La suma de los 5 numeros es: ”+ suma);
}
}
int[] matriz = new int[n] ; -----> si luego colocamos [Link] nos devuelve el valor “n”;

ARREGLO TIPO FOR IT:


For ( (tipo de arreglo) i : nombre de arreglo) {
[Link](“nombre: “+i) ; el i = dato del arreglo
CREACION DE CLASE Y OBJETO
public class Coche (){ //public : modificador de acceso , Coche: creación de clase
String color;
String marca;
int km;
public static void main(String[] args){
Coche coche1= new Coche(); //creación de objeto 1;
[Link] = “Blanco”;
[Link]=”audi”;
[Link]=0;
[Link](“El coche es: “ + [Link] + “ de marca “ +[Link]+ “y
“+[Link] + “ km “);
}
}

Common questions

Con tecnología de IA

The 'switch' statement in Java offers a streamlined alternative to multiple 'if-else' statements by evaluating a single expression against multiple potential cases, executing the associated blocks of code upon matching a case. It provides a clear, organized structure, especially when handling numerous potential values. Its main limitation is that the expression in a switch statement must evaluate to a char, byte, short, int, String, or an enum, limiting its flexibility compared to 'if-else' statements, which can handle more complex and varied conditions. Additionally, switch cases fall through by default unless terminated with a 'break', which might lead to unintended execution of subsequent cases .

In Java, using 'final' when declaring a variable implies that its value cannot be changed once it has been assigned. This immutability ensures data protection and stability, as constants are used throughout the program to represent fixed values. When 'final' is applied to methods, it prevents these methods from being overridden in subclasses, thus preserving the intended behavior of those methods across different class hierarchies. This can be crucial when guaranteeing the consistent execution of critical functionality, ensuring that the behavior implemented is not inadvertently altered through inheritance .

Encapsulation in Java is essential for class design as it enables the bundling of data (fields) and methods (functions) that operate on the data into a single unit known as a class. It restricts direct access to some of an object's components, hence promoting controlled manipulation of the object’s state and protecting against unauthorized or incorrect changes. Encapsulation is achieved by declaring fields as private and providing public getter and setter methods to access and update them. This practice enhances software reliability by maintaining data integrity and enabling modularity, which simplifies debugging and maintenance. It also supports abstraction, allowing an object to hide its internal state and details while exposing only what is necessary .

User interaction through graphical dialogs in Java is crucial for applications requiring user inputs or delivering information in a more intuitive and interactive manner. The JOptionPane class facilitates this by providing standard dialog boxes within a graphical user interface (GUI). Users can enter data and receive information through dialogs like message, input, confirmation, and option dialogs, making applications more user-friendly and interactive. JOptionPane simplifies the implementation of GUI dialog components, enhancing user experience with minimal programming overhead .

Input operations for numeric data in Java using the Scanner class involve creating a Scanner object that reads from System.in. The syntax involves calling methods like nextInt() for integers, nextFloat() for floating-point numbers, and nextDouble() for double floating-point numbers. For output, the System.out.println() method is commonly used to display data. For example, creating a Scanner object and using it to read an integer would be: Scanner entrada = new Scanner(System.in); int numero = entrada.nextInt(); System.out.println("Escriba un numero entero: " + numero).

In Java, the increment operator '++' increases a variable's value by one, while the decrement operator '--' decreases it by one. The difference between pre- and post- variations lies in when the increment or decrement takes effect. Pre-increment (++x) and pre-decrement (--x) operators increase or decrease the value before the value is used in the expression. Post-increment (x++) and post-decrement (x--) operators perform the operation after the current expression has been evaluated. For example, if x is 5, int j = x++; results in j being 5, but x becomes 6, whereas int k = ++x; results in both k and x being 6 when x originally was 5 .

Primitive data types in Java are the most basic data types and include byte, short, int, long, float, double, char, and boolean. They are not objects and hold their values directly within the variable. Non-primitive data types, also known as object reference types, include arrays, classes, interfaces, etc., and these store references to the actual data. This distinction is important because primitive types offer higher performance due to their simplicity, while non-primitive types provide flexibility and the ability to represent more complex data structures, carrying methods that can operate on the data itself .

Arrays in Java are declared using the syntax: <data type>[] <array name> = new <data type>[size]; for example, 'int[] numbers = new int[5];'. To use arrays, individual elements can be accessed through their index, starting at 0. Multidimensional arrays, such as 2D arrays, can be created with declarations like 'int[][] matrix = new int[3][3];', where elements are accessed through two indices representing the row and column respectively. Arrays store multiple items of the same data type efficiently and provide an organized way to access and manage data collections .

The Java 'Math' class provides a comprehensive set of static methods for performing mathematical operations, such as calculating square roots using Math.sqrt(), powers using Math.pow(), rounding using Math.round(), and generating random numbers with Math.random(). This class is relevant as it allows programmers to implement complex calculations and numeric transformations directly within Java applications without needing additional libraries. Common applications of the Math class include scientific computing, financial simulations, and graphical applications where precision in calculations is required .

Object creation and constructors are fundamental in Java's object-oriented programming as they define how objects are instantiated and initialized. Constructors allow the initialization of an object with a specific state by assigning values to its properties. This practice encapsulates the state information within objects, making data management more modular and organized. It also promotes one of the core principles of object-oriented programming, encapsulation, which protects data integrity by controlling its access and modification through methods. This system underpins the structure of Java applications, providing flexibility, scalability, and ease of maintenance .

También podría gustarte