1 Introduction To Programming in Java p2 v4
1 Introduction To Programming in Java p2 v4
• Lecture 1 Review
• More types
• Methods
• Conditionals
Data Types
Kinds of values that can be stored and manipulated.
More usuals:
Primitives:
/*
numPeq1 = numPeq1 + 1;
numPeq2 = numPeq2 + 1;
Number = Number + 1;
//remove multiline comments and recompile
// and run the program
*/
//in the next block the values are displayed on the screen
System.out.println( "integer is " + numPeq1 );
System.out.println( "the integer is " + numPeq2 );
System.out.println( "integer is " + Number );
System.out.println( "bigInteger is " + bigInteger );
System.out.println( "integer1 with decimals is " + integer1Decimals );
System.out.println( "integer2 with decimals is " + integer2Decimals );
System.out.println( "the symbol is " + symbol );
System.out.println( "string is " + str1ng );
Variables
Named location that stores a value
Example:
String a = “a”;
String b = “letter b”;
a = “letter a”;
String c = a + “ and ” + b;
Operators
Symbols that perform simple computations
Assignment: =
Addition: +
Subtraction: –
Multiplication: *
Division: /
Assignment solution
public class GravityCalculator {
public static void main(String[] args) { // begin main method
double gravity = -9.81;
double initialVelocity = 0.0;
double fallingTime = 10.0;
double initialPosition = 0.0;
double finalPosition = 0.5 * gravity * fallingTime * fallingTime;
finalPosition = finalPosition + initialVelocity * fallingTime;
finalPosition = finalPosition + initialPosition;
System.out.println("An object's position after " + fallingTime + " seconds is " +
finalPosition + " m." );
} // end main method
} // end of class GravityCalculator
• You need to import a package that contains a particular class, the Scanner class.
//console program that adds two integers and displays the result
//The java.util package is needed
import java.util.Scanner; //and use the Scanner class
//declaration of variables
int num1; //first number to add
int num2; //second number to add
int result; //result of the sum
read.close();
} //end main method
} //end of class AddTwoNums
fuente: http://lineadecodigo.com/java/sumar-dos-numeros-con-java/
If you don't close the read object after you've finished using it, there may be some negative implications for your
program. Proper closing of the Scanner object is a good practice to ensure proper resource management and
prevent potential problems.
Memory leaks: If you don't close the Scanner class object, the underlying resources might not be freed, which could cause a memory leak.
Every time you create a new Scanner object, a memory buffer is reserved to store the input. If these resources are not freed properly, your
program could run out of memory over time.
Input stream blocking: In some cases, not closing the Scanner object could cause the input stream to become blocked, meaning that you
won't be able to receive any more input from the user or from other input streams (such as files). This could result in unexpected behavior
of your program.
Potential Conflicts: If your program tries to create another Scanner object in the same input stream without closing the previous one, it
could cause conflicts and errors when reading data.
Assignment.
Tomando como base el programa AddTwoNums.java haga otro programa que: a) En lugar de sumar los dos
números ahora los reste y los multiplique; b) muestre ambos resultados; c) guarde el programa y la clase
principal como DosNumsOperaciones1_suMatricula.
Tomando como base el programa AddTwoNums.java haga otro programa que: a) Ahora divida el primero entre
el segundo y luego divida el segundo entre el primero; b) muestre ambos resultados; c) guarde el programa y la
clase principal como DosNumsOperaciones2_suMatricula.
Tomando como base el programa AddTwoNums.java haga otro programa que obtenga la división modular (resto
de la división o residuo de la división) a) del primero entre el segundo; b) del segundo entre el primero; c)
muestre ambos resultados; c) guarde el programa y la clase principal como DosNumsOperaciones3_suMatricula.
Tomando como base el programa AddTwoNums.java haga otro programa que: a) permita la entrada de un tercer
número; b) sume el resultado de la primera suma con el tercer número; c) La variable de la tercera suma se
llame resul_final; d) muestre los resultados de las dos sumas; e) guarde el programa y la clase principal como
SumaTresNums_suMatricula.
Assignment.
Find instructions for entering values from the console for the data types char, short, long, float, double, and String
object.
//console program that adds three integers and displays the result
//The java.util package is needed
import java.util.Scanner; //and use the Scanner class
//declaration of variables
int num1; //first number to add
float num2; // second number to add
double num3; //third number to add
int result; //result of the sum
read.close();
Outline
• Lecture 1 Review
• More types
• Methods
• Conditionals
Division
Division (“/”) operates differently on integers and on doubles!
Example:
double a = 5.0/2.0; // result a = 2.5
double d = 5/2; // d = 2.0
int b = 4/2; // b = 2
int c = 5/2; // c = 2
Order of Operations
Precedence like math, left to right Right hand side of = evaluated first.
Conversion by casting
int a = 2; // a = 2
double a = 2; // a = 2.0 (Implicit)
double a = 3.5f; // a = 3.5 (Implicit)
Outline
• Lecture 1 Review
• More types
• Methods
• Conditionals
Methods
public static void main( String[ ] arguments )
System.out.println( ”hi” );
Adding Methods
public static void NAME_Method() {
STATEMENTS
A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if
you have written instructions to draw a circle in the method, it will do that task. You can insert values or
parameters into methods, and they will only be executed when called. Source.
threeLines();
threeLines();
Parameters
STATEMENTS
System.out.println( x*x );
int value = 2;
printSquare( value );
printSquare( 3 );
printSquare( value*2 );
System.out.println( x*x );
printSquare( "hello" );
printSquare( 5.5 );
System.out.println( x*x );
printSquare( (double) 5 );
Multiple Parameters
[…] NAME_Method( DATA_TYPE NAME1 , DATA_TYPE NAME2 ) {
STATEMENTS
times ( 2, 2 );
times ( 3, 4 );
} // end main method
Return Values
public static DATA_TYPE NAME_Method() {
STATEMENTS
return EXPRESSION;
void means “no type” and does not have a return expression, like the previous examples.
double squa_re;
squa_re = x*x;
return squa_re;
System.out.println( calcSquare( 5 ) );
return x*x;
System.out.println( square( 5 ) );
System.out.println( square( 2 ) );
Classroom Exercises
Make a program that calculates the value of “y” in the following equation, y = Ax2 + Bx + C. Use the following
integer values, A = 2, B = -3, C = 5, x = 2. Use a method to do the calculation and return to return the result to the
main method. The expected value of y = 7.
Make a program that calculates the average of 3 whole degrees, which are 85, 93 and 65. The average
calculation must be done in a method, use return to return the result to the main method. The expected value of
Once completed, try the program with the values 85, 93 and 66; 85, 93 and 67. Why is the average the same if
the last grade was modified twice?
Variable Scope
Variables live in the block “{ }” where they are defined (scope)
x = x * x;
int x = 5;
printSquare( x );
if ( x == 5 ) {
x = 18;
y = 72;
} // end if
newValues( x, y );
Assignment.
To practice the subject of methods with parameters, you are going to convert the 4 programs from the previous
homework to programs that use methods with parameters.
File names can be the same by adding an underscore, an M, a y and a P, m for methods and p for parameters.
Mathematical Functions
Math.sin( x )
Math.cos( Math.PI / 2 )
Math.pow( 2, 3 )
Math.log( Math.log( x + y ) )
• Using the formula y = ax2 + bx + c, write the program that calculates the value of "y" for any values of x, a,
b, and c.
Exercise 1
Secondary method
- Receive values with parameters method (Parameters)
- Do calculations area_sc = ¿?
- Return results to main method return area_sc
Main method
- Send values using arguments method (arguments)
- Receives values (results) with the call to the method (arguments) // you can assign the call to a variable
secondary method
Use System.out to display results //use the variable of one step before
- Displays results on screen
Note: To distinguish the arguments from the parameters, add to the names _m
Clues: 3.1416 and 3.4 radio, area is 36.3168 u2 for main; _sc for secondary
3.1416 and 5.2 radio, area is 84.948 u2
Exercise 2
Secondary method
- Receive values with parameters method (Parameters)
- Do calculations y_sc = ¿?
- Return results to main method return y_sc
Main method
- Send values using arguments method (arguments)
- Receives values (results) with the call to the method (arguments) // you can assign the call to a variable
secondary method
Use System.out to display results //use the variable of one step before
- Displays results on screen
Note: To distinguish the arguments from the parameters, add to the names _m
Clues (a, b,c, x): 2.3, 3.2, 1.4, 1.8; y = 14.612 for main; _sc for secondary
(a, b,c, x): 3.5, 1.3, 2.8, 2.4; y = 26.08
The notepad++ can be configured to allow us to compile and run the programs with a simple combination of keys
(shortcut).
Menu “Ejecutar”
OK button
Suggestion: ALT + SHIFT + R key combination to run a program. R for “run” a program.
Outline
• Lecture 1 Review
• More types
• Methods
• Conditionals
if statement
if ( CONDITION ) {
Instructions codeblock 1
if ( x > 5 ) {
} // end if
test( 4 );
test( 5 );
test( 6 );
Comparison operators
x > y: x is greater than y
x == y: x equals y
Boolean operators
&& : logical AND
|| : logical OR
Truth table for logical operations and, or taking the input values as P and Q.
P Q AND OR
T T T T
T F F T
F T F T
F F F F
Example.
if (x < 9) { …
… }
else
if (CONDITION) {
Instructions codeblock 1
} else {
Instructions codeblock 2
if (x > 5) {
} else {
} // end if
test( 4 );
test( 5 );
test( 6 );
else if
if (CONDITION1) {
codeblock 1
} else if (CONDITION2) {
codeblock 2
} else if (CONDITION3) {
codeblock 3
} else {
codeblock 4
if ( x > 5 ) {
} else if ( x == 5 ) {
} else {
test( 6 );
test( 5 );
test( 4 );
Classroom Exercises
Make a program that allows you to enter (from keyboard) the name and age of two people and that shows on the
screen the name of the older of the two.
Clues: 1. Monica, 25; Oscar, 29. Older is Oscar. 2. Jorge, 36, Diana, 26. Older is Jorge.
Develop a program in which according to a numerical grade shows its equivalent in letter according to the
following table. You could see this.
Questions?
Assignment: FooCorporation
FooCorporation needs a program to calculate how much to pay their employees.
Pay is obtained by multiplying hours worked by hourly pay. The base pay must be no less than $8.00/hour. (Do a
validation). Overtime is more than 40 hours, and paid 1.5 times base pay. The maximum number of hours must be
no more than 60/week. (Do a validation).
Use a particular method to do calculations and to display results, use the if statement where necessary or
convenient. The main method will call to method and will send values to method. Arguments to send will be base
pay and hours worked.
Reminder
• Write your own code
Conversion by method
int to String:
String five = 5; // ERROR!
String five = Integer.toString (5);
String five = “ ” + 5; // five = “5”
String to int:
int foo = “18”; // ERROR!
int foo = Integer.parseInt ( “18” );
Comparison operators
Do NOT call == on doubles! EVER.
double a = Math.cos (Math.PI / 2);
double b = 0.0;
a = 6.123233995736766E-17
Solved exercises
Make a program that allows you to enter the name and age of two people and that shows on the screen which of
the two is older.
import java.util.Scanner;
public class CadenaCaracteres1_v3 {
public static String edadMayor ( int edd_1, String nam_1, int edd_2, String nam_2) {
String nam_sc;
if (edd_1 > edd_2) {
nam_sc = nam_1;
// variable declaration
String nombre1, nombre2;
int edad1, edad2;
// input data
System.out.print( "name 1st person " );
nombre1 = leer.next();
System.out.print( "age 1st person ");
edad1 = leer.nextInt();
System.out.print( "name 2nd person " );
nombre2 = leer.next();
System.out.print( "age 2nd person " );
edad2 = leer.nextInt();
// method call
String name;
name = edadMayor ( edad1, nombre1, edad2, nombre2 );
// display results
System.out.println( "la persona de mayor edad es " + name );
leer.close();
import java.util.Scanner;
public class Calif_num_a_calif_letra {
public static String convNum2Letra ( int cal) {
return cal_let;
} // end of convNum2Letra method
// variable declaration
int cal_num;
// input data
System.out.print( "give me the calif from 0 to 100 " );
cal_num = leer.nextInt();
// method call
String cal_letra;
cal_letra = convNum2Letra (cal_num);
leer.close();
2. Make a program that identifies whether a number is even or odd by displaying a message on the screen
3. Make a program that determines which is the largest of three different numbers integers. This exercise can
be done in several ways, the most obvious is the one in which successive comparisons are made.
4 5 10 2 num2
5 5 2 10 num3
6 2 5 10 num3
4. Make a program that identifies if a number is divisible by 3 exactly (it means that the remainder is zero) by
displaying a message on the screen
5. Make a program that identifies if a number is divisible by 3 exactly (it means that the remainder is zero) by
displaying a message on the screen; is divisible by 9 exactly, and if is divisible by 3 and 9 at the same
time.
Exercise 1 OPTION1
Secondary method Since the methods we have seen can only return one value, we will have to use
two methods, one to return the average and other to return the status.
- Receive values with parameters
- calculate Average
method1 (Parameters)
- Based on the minimum passing rate,
determine the student status (pass or fail) Prom = ( cal1 + cal2 + cal3 ) / 3
- Return results to main method return Prom
OPTION2
method1 (Parameters the califs)
Prom = ( cal1 + cal2 + cal3 ) / 3
return Prom
Exercise 2 Since the methods we have seen can only return one value, we will have to use
two methods, one to return the remainder and other to return the type of
Secondary method
number.
- Receive values with parameters
method1 (Parameters the number)
- calculate the remainder
rem = num % 2
- Determine if the number is even or odd based
return rem
on the remainder of the division.
- Return results to main method
method2 (Parameters only rem)
if ( rem == 0 )
Main method
True? type = “Even” False? type = “odd”
- Send values using arguments
return type
- Receives values (results) with the call to the
secondary method
- Displays results on screen main method (arguments)
declaration of variables
Clues: 11 is odd; 14 is even request input data
// call each method
Rem = method1 (argument the number)
Type = method2 (arguments only Rem)
display results on screen
This teaching material is based on 6.092 Introduction to Programming in Java, January (IAP) 2010, which is available at MIT OpenCourseWare:
http://ocw.mit.edu, therefore has the Creative Commons license mentioned in https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
For information about citing 6.092 Introduction to Programming in Java or yours Terms of Use, visit: http://ocw.mit.edu/terms.