Study Sheet for CPS 1231
Unit 1/2:
Intro to Java
Java like other programming langauages is case sensitive
there are 3 types of errors in java
syntax
logical
runtime
line one of your prorgram will define a class. Each java prorgram has at least one class
*class names always start with a Uppercase letter
line two of your prorgram is your main method. This is where your prorgram is executed from
Example of a main method
public static void main(String[] args){
} *when you use a bracket you must always close it with a bracket
Remember to save your prorgram as a .java file
Unit 3: Variables, Data Types, and Arithmetic Operators
What are variables? Variables are used to represent values that may be changed in the program
All of the data types you might see
byte
short
int
boolean
long
float
double
char
different arithmetic operators
Unit 4: Conditional Statements
Conditional statements determine which statements to execute based on their condition
Unit 5: Logical Operators, Switch Statements, and Expressions
What are logical operators? Logical operators are used to combine several conditions and create boolean expressions
Examples of logical operators
!
&&
^
||
Switch statements execute statements based on the value of a variable or an expression
Switch statements must always result a value of char, int, short, and byte
Unit 6: Mathematical functions, Characters, and string functions
Java provides many useful methods in the Math class for preforming common mathematical functions
Trigonomic methods in Math class in java:
sin,cos, tan, asin, acos, and many more
*Math.acos(0.5) returns 1.0472
Rounding methods in Math class in java:
ceil(x), floor(x), rint(x), and round(x)
*Math.ceil(2.1) returns 3.0
*Math.floor(2.1) returns 2.0
Random methods in Math class in java:
(int)(Math.random() * 10) =
*returns a random integer from 0 to 9
50 + (int)(Math.random() * 50) =
*returns a random integer from 50 to 99
Unit 7: Review for Midterm(Chapters 1-4)
Unit 8: Repetition Statements
Loops can be used to tell a program to execute statements repeatedly
Problem example
You want to print out "Welcome to Java!" one hundred times. It would be a tedious task to write the same or copy the same string one hundred times.
How would you solve this? loop
What are loops? Loops control how many times an operation or a sequence of operations is preformed in succession.
while loop
while loop executes statements repeatedly while the statement is true
Unit 9: For Loop, Nested Loop, Break and Continue
For loops can be written like this
there are also variations of for loops that look like this
Key to remember when to use for or while loop
Loops can be nested inside other loops, this is known as a nested loop. Nested loops consist of outer loops and one or more inner loops.
Break and continue keywords provide additional controls in loops.
Breaks are used to terminate loops.
Continue breaks out of an iteration and continues to the end of the loop body
Unit 10: Methods
What is a method? A method consists of a method name, parameters, return value type, and body
To execute a method you must first call it. The program that calls a method is called a caller
to call a method that returns a value
int larger = max(3, 4);
this call max(3, 4) and assigns the result of the method to the variable larger
to call a method that returns void
System.out.println("Welcome to Java!");
the method println returns void
Unit 11: Method Overloading, Scope of Variables
Method overloading enables you to define methods with the same name as long as the parameter lists are different
If you needed determine which two floating-point numbers has the maximum value the solution would be to create another method with the same name but different parameters.
The scope of a variable is the part of the prorgram where the variable can be referenced
Unit 12/13/14: Arrays
Array sizes are fixed when they're created
To use an array in your program declare a variable to reference the array and specify the array's element type
example on declaring an array variable
elementType[] arrayRefVar;
or
elementType arrayRefVar[];
*although not encouraged it's still allowed
when proccessing an array you will often use a for loop
When wanting to sort a list in ascending order. Selection sort finds the smallest number in the list and swaps it with the first element. It then finds the smallest number remaining and swaps it with the second element, and so on.
Unit 15: Final
Hoja de Estudia para CPS 1231
Unidad 1/2:
introduccion a Java
Java es como otro lenguages de programacion y es distinguida por mayusculas y minusculas
Existen tres tipos de errores en java
syntax
logical
runtime
linea uno de tu prorgrama va definir una clase. Cada programa de java tiene una clase
*nombres de clases siempre comienzan con una letra mayuscula
linea dos de tu prorgama es el metodo principal. Aqui es donde tu programa es ejecutado
ejemplo de el metodo principal
public static void main(String[] args){
} *caundo usen un bracket lo tienen que cerrar con un bracket
Recuerdense que siempre tienen que guardar su programa como .java file
Unidad 3: Variables, tipos de datos, y operadores aritmeticos
Que son variables? Variables son usado para representar valores que pueden ser cambiado en el programa
Todos los tipos de datos que pueden ayar
byte
short
int
boolean
long
float
double
char
diferente operadores aritmeticos
Unidad 4: Declaraciones Condicionales
Declaraciones condicionales determinen caul declaraciones son ejecutada establecido por su condicion
Unidad 5: Operadores Logicos, Switch Statements, y expresiones
Que son operadores logicos? Operadores logicos son usado para combinar varios condiciones y crear expresiones booleanas
Ejemplos de operadores logicos
!
&&
^
||
Switch statements ejecutan declaraciones establecido por el valor del variable o expresion
Switch statements siempre resultan en un valor de char, int, short, y byte
Unidad 6: Funciones Matematicas, Caracteres, y Funciones de Cadena
Java proporciona muchos metodos que pueden ser usada en la clase de math. Estas clases son usada para preformar funciones matematicas comunes
Metodos trigonometrico en la clase de matematicas
sin, cos, tan, asin, acos, y muchos mas
*Math.acos(0.5) devolve 1.0472
Metodos de redondeo en la clase de matematicas
ceil(x), floor(x), rint(x), and round(x)
*Math.floor(2.1) devuelve 2.0
*Math.ceil(2.1) devuelve 3.0
Metodos aleatorios en la clase de matematicas
(int)(Math.random() * 10) =
devuelve un numera de 0 a 9
50 + (int)(Math.random() * 50) =
devuelve un numero de 50 a 99
Unidad 7: Revision para el midterm(Capitulos 1-4)
Unidad 8: Declaraciones de Repeticion
Los bucles pueden ser usado para decirle al programa que ejecute declaraciones repetidamente
Ejemplo de problema
Usted quiere imprimir "Bienvenido a Java!" cien veces. Seria una tarea tediosa escibir lo mismo o copiar la misma cadena cien veces.
Como resolveria esto? con un bucle
Que son bucles? Bucles controlan cuantas veces se realiza una operacion o una secuencia de operaciones en sucesion
mientras bucle
mientras bucles ejecutan declaraciones repetidamente mientras la declaracion es verdadera
Unidad 9: For Loop, bucle anidado, descanso, y seguir
For loops se pueden escribir asi
Tambien hay variaciones de for loops que se ven asi
Clave para recordar caundo esta usando bucle anidado
Bucles pueden ser anidido dentro de otros bucles, esto se conoce como bucle anidado. Los bucles anidados tienen bucles exteriores y uno o mas bucles interiores
Descanso y seguir son controles adicionales en bucles
Descanso se utilizan para terminar bucles
Continuar sale de una iteracion y continua hasta el final del cuerpo del bucle
Unidad 10: Metodos
Que es un metodo? Un metodo tiene un nombre, parametros, tipo de valor de retorno, y un cuerpo
Para ejecutar un metodo, primero debe llamarlo. El programa que llama a un metodo se llama llamador
para llamar a un metodo que devuelve un valor
int mayor= max(3,4);
esta llamada max(3,4) y asigna el resultado del metodo a la variable mayor
para llamar a un metodo que devuelve vacio
System.out.println("Bienvenido a Java!");
El metodo println devuelve vacio
Unidad 11: Sobrecarga de metodos, Alcance de las Variables
La sobrecarga de metodos le permite definir metodos con el mismo nombre pero que las listas de parametros sean diferentes.
Si necesita determinar que dos numeros de coma floatante tienen el valor maximo, la solucion seria crear otro metodo con el mismo nombre pero con diferentes parametros.
El alcance de un variable es la parte del programe donde se puede hacer referencia al variable
Unidad 12/13/14 Matrices
Los tamaños de matriz se fijan cuando se crean
Para usar una matriz en su programa, declare una variable para hacer referencia a la matriz y especifique el tipo de elemento de la matriz
ejemplo sobre la declaracion de un variable de matriz
tipoElemento[] arrayRefVar;
o
tipoelemento arrayRefVar[];
* aunque no se recomienda, todavía está permitido
al procesar una matriz, a menudo usará un for loop
Al querer ordenar una lista en orden ascendente. La ordenación por selección encuentra el número más pequeño de la lista y lo intercambia con el primer elemento. Luego encuentra el número más pequeño que queda y lo intercambia con el segundo elemento, y así sucesivamente.
Unidad 15: Final de clase
Study Sheet for CPS 2231
Loops, and Methods
While loop executes statements repeatedly while the statement is true
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
While i is less than 5 then the statement is true and the loop will continue
Loops can be nested inside other loops, this is known as a nested loop. Nested loops consist of outer loops and one or more inner loops.
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
Methods are a block of code which only runs when it is called
Methods allow data to be passed into a method, known as parameters
When should you use methods? When you're reusing code.
public class Main { //name of the method
static void myMethod() {
// code to be executed
}
}
1-D and 2-D arrays
Array sizes are fixed when they're created
Arrays are used to store a collection of data
example on declaring an array variable
elementType[] arrayRefVar;
or
elementType arrayRefVar[];
*although not encouraged it's still allowed
example of declaring a two-dimensional array
elementType[][] arrayRefVar;
elementType arrayRefVar[][]; // Allowed, but not preferred
declaring a two-dimensional array that yields an int-value
int[][] matrix;
or “int matrix[][]; // This style is allowed, but not preferred”
Intro to Object-Oriented Programming
What are the advantages of OOP over procedural programming?
Provides a clear structure for the prorgams
OOP is faster and easier to execute
makes it possible to create full reusable applications with less code and shorter devolopement time
Classes and objects are the main aspects of object-oriented prorgamming
An example of a class would be car
An example of an object would be Audi, Toyota, and Kia
*Midterm Week
Inheritance
Object-oriented programming allows you to define new classes from existing classes. This is called inheritance
Inheritance is an important and powerful feature for reusing software
Inheritance enables you to define a general class which is called a superclass and later extend it to more specialized classes defined as subclasses
In the example below the car class (subclass) inherits the attributes and methods from the vehicle class (superclass)
class Vehicle {
protected String brand = "Ford";
// Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
// Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Polymorphism
One of the three pillars of object-oriented programming
Polymorphism means that a variable of a supertype can refer to a subtype object
Example of polymorphism:
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
Recursion-
recursion characterisitics
if-else
Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case
To solve a problem using recursion, you break it into subproblems. Each subproblem is the same as the original problem, but just smaller in size.
Exceptions
Exceptions are objects, and objects are defined using classes
The root class for exceptions is java.long.Throwable
Exception handling in java consists of declaring exceptions, throwing exceptions, and processing exceptions.
To delcare an exception:
public void myMethod() throws IOException
To throw an exception:
public void myMethod() throws Exception1, Exception2, ... ExceptionN
*Final Exam Week
Hoja de estudio para CPS 2231
Bucles, y Métodos
Mientras bucles ejecutan declaraciones repitadamente mientras la declaracion es verdadera
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Mientras i sea menos que 5, la declaracion es verdadero y el bucle continuará
Bucles pueden estar dentro de otros bucles, esto es connocido como bucle anidado. Bucles anidados consisten de un bucle afuera y uno o mas bucles adentro
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
Metodos son un bloque de codigo que solo ejecuta caundo es llamado
Metodos dejan que datos passen dentro de un metodo, conocidos como parámetros
Caundo se usan los metodos? Caundo esta reutilizando codigo
public class Main { //name of the method
static void myMethod() {
// code to be executed
}
}
1-D and 2-D Matrizes
Los tamanos de matrizes son fijado caundo son creado
Matrizes son utilizado para guardar una coleccion de datos
Ejemplo sobre la declaracion de un variable de matriz
elementType[] arrayRefVar;
elementType arrayRefVar[];
*no se recomienda pero es permitido
Ejemplo declarando una matriz bidimensional
elementType arrayRefVar[][];
Declarando una matriz bidimensional que produce un valor int
int[][] matrix;
or “int matrix[][];
Introducción a la programación orientada a objetos
Caules son las ventajas de OOP sobre la programacion procedimental?
Proporciona una estructura clara para los programas
OOP es mas rapido y mas facil para ejecutar
hace posible crear aplicaciones reutilizables con menos codigo y un tiempo de desarollo mas corto
Clases y objetos son los aspectos principales de la programacion orientada a objetos
Un ejemplo de una clase seria un coche
Un ejemplo de un objeto seria Audi, Toyota, y Kia
*Midterm Week
Herencia
La programacion orientada a objetos le permite definir nuevas clases de clases existentes. Esto se llama herencia.
La Herencia es una caracteristica importante y poderosa para reutilizar software
Herencia le permite definir una clase general que se llama una superclass y despues extendera mas clases mas especializadas definidas como subclases
En el ejemplo, la clase de automovil (subclase) hereda los atributos y metodos de la clase vehiculo (superclase)
class Vehicle {
protected String brand = "Ford";
// Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
// Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Polimorfismo
Uno de los tres pilares de la programacion orientada a objetos
Polimorfismo significa que un variable de un supertipo puedo referirse a un objeto de subtipo
Ejemplo de polimorfismo
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
Recursion
Las caracteristicas de recursion
Cada llamada de recursion reduce el problema original,
Para resolver un problema usando recursion, lo divdes en subproblemas. Cada subproblema es el mismo que el problema original, pero de menor tamano
Excepciones
Las excepciones son objetos, y los objetos se definen usando clases
La clase raiz para excepciones es java.long.Throwable
El manejo de excepciones en java consiste en declarar excepciones, lanzar excepciones, y procesar excepciones
Para del una excepcion:
public void myMethod() throws IOException
Para lanzar una excepcion:
public void myMethod() throws Exception1, Exception2, ... ExceptionN
*Final Exam Week