SlideShare a Scribd company logo
6.092: Intro to Java
2: More types, Methods,
Conditionals
Outline
•  Lecture 1 Review
•  More types
•  Methods
•  Conditionals
Types
Kinds of values that can be stored and
manipulated.
boolean: Truth value (true or false).
int: Integer (0, 1, -47).
double: Real number (3.14, 1.0, -2.1).
String: Text (“hello”, “example”).
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: /
class GravityCalculator {
public static void main(String[] args) {
double gravity = -9.81;
double initialVelocity = 0.0;
double fallingTime = 10.0;
double initialPosition = 0.0;
double finalPosition = .5 * gravity * fallingTime *
fallingTime;
finalPosition = finalPosition +
initialVelocity * fallingTime;
finalPosition = finalPosition + initialPosition;
System.out.println("An object's position after " +
fallingTime + " seconds is " +
finalPosition + “ m.");
}
}
finalPosition = finalPosition +
initialVelocity * fallingTime;
finalPosition = finalPosition + initialPosition;
OR
finalPosition += initialVelocity * fallingTime;
finalPosition += initialPosition;
Questions from last lecture?
Outline
•  Lecture 1 Review
•  More types
•  Methods
•  Conditionals
Division
Division (“/”) operates differently on
integers and on doubles!
Example:
double a = 5.0/2.0; // a = 2.5
int b = 4/2; // b = 2
int c = 5/2; // c = 2
double d = 5/2; // d = 2.0
Order of Operations
Precedence like math, left to right
Right hand side of = evaluated first
Parenthesis increase precedence
double x = 3 / 2 + 1; // x = 2.0
double y = 3 / (2 + 1); // y = 1.0
Mismatched Types
Java verifies that types always match:
String five = 5; // ERROR!
test.java.2: incompatible types
found: int
required: java.lang.String
String five = 5;
Conversion by casting
int a = 2; // a = 2
double a = 2; // a = 2.0 (Implicit)
int a = 18.7; // ERROR
int a = (int)18.7; // a = 18
double a = 2/3; // a = 0.0
double a = (double)2/3; // a = 0.6666…
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() {
STATEMENTS
}
To call a method:
NAME();
class NewLine {
public static void newLine() {
System.out.println("");
}
public static void threeLines() {
newLine(); newLine(); newLine();
}
public static void main(String[] arguments) {
System.out.println("Line 1");
threeLines();
System.out.println("Line 2");
}
}
class NewLine {
public static void newLine() {
System.out.println("");
}
public static void main(String[] arguments) {
System.out.println("Line 1");
threeLines();
System.out.println("Line 2");
public static void threeLines() {
newLine(); newLine(); newLine();
}
}
}
public static void main(String[] arguments) {
System.out.println("Line 1");
threeLines();
System.out.println("Line 2");
public static void threeLines() {
newLine(); newLine(); newLine();
}
class NewLine {
public static void
""
newLine() {
System.out.println( );
}
}
}
Parameters
public static void NAME(TYPE NAME) {
STATEMENTS
}
To call:
NAME(EXPRESSION);
class Square {
public static void printSquare(int x) {
System.out.println(x*x);
}
public static void main(String[] arguments) {
int value = 2;
printSquare(value);
printSquare(3);
printSquare(value*2);
}
}
class Square2 {
public static void printSquare(int x) {
System.out.println(x*x);
}
public static void main(String[] arguments) {
printSquare("hello");
printSquare(5.5);
}
}
What’s wrong here?
class Square3 {
public static void printSquare(double x) {
System.out.println(x*x);
}
public static void main(String[] arguments) {
printSquare(5);
}
}
What’s wrong here?
Multiple Parameters
[…] NAME(TYPE NAME, TYPE NAME) {
STATEMENTS
}
To call:
NAME(arg1, arg2);
class Multiply {
public static void times (double a, double b) {
System.out.println(a * b);
}
public static void main(String[] arguments) {
times (2, 2);
times (3, 4);
}
}
Return Values
public static TYPE NAME() {
STATEMENTS
return EXPRESSION;
}
void means “no type”
class Square3 {
public static void printSquare(double x) {
System.out.println(x*x);
}
public static void main(String[] arguments) {
printSquare(5);
}
}
class Square4 {
public static double square(double x) {
return x*x;
}
public static void main(String[] arguments) {
System.out.println(square(5));
System.out.println(square(2));
}
}
Variable Scope
Variables live in the block ({}) where they
are defined (scope)
Method parameters are like defining a
new variable in the method
class SquareChange {
public static void printSquare(int x) {
System.out.println("printSquare x = " + x);
x = x * x;
System.out.println("printSquare x = " + x);
}
public static void main(String[] arguments) {
int x = 5;
System.out.println("main x = " + x);
printSquare(x);
System.out.println("main x = " + x);
}
}
class Scope {
public static void main(String[] arguments) {
int x = 5;
if (x == 5) {
int x = 6;
int y = 72;
System.out.println("x = " + x + " y = " + y);
}
System.out.println("x = " + x + " y = " + y);
}
}
Methods: Building Blocks
•	 Big programs are built out of small methods
•	 Methods can be individually developed, tested and
reused
•	 User of method does not need to know how it works
•	 In Computer Science, this is called “abstraction”
Mathematical Functions
Math.sin(x)
Math.cos(Math.PI / 2)
Math.pow(2, 3)
Math.log(Math.log(x + y))
Outline
•  Lecture 1 Review
•  More types
•  Methods
•  Conditionals
if statement
if (CONDITION) {
STATEMENTS
}
public static void test(int x) {
if (x > 5) {
System.out.println(x + " is > 5");
}
}
public static void main(String[] arguments) {
test(6);
test(5);
test(4);
}
Comparison operators
x > y: x is greater than y
x < y: x is less than y
x >= y: x is greater than or equal to x
x <= y: x is less than or equal to y
x == y: x equals y
( equality: ==, assignment: = )
Boolean operators
&&: logical AND
||: logical OR
if ( x > 6 && x < 9) {
if (x > 6) {
…
if (x < 9) {
}
…
}
}
else
if (CONDITION) {
STATEMENTS
} else {
STATEMENTS
}
public static void test(int x) {
if (x > 5) {
System.out.println(x + " is > 5");
} else {
System.out.println(x + " is not > 5");
}
}
public static void main(String[] arguments) {
test(6);
test(5);
test(4);
}
else if
if (CONDITION) {
STATEMENTS
} else if (CONDITION) {
STATEMENTS
} else if (CONDITION) {
STATEMENTS
} else {
STATEMENTS
}
public static void test(int x) {
if (x > 5) {
System.out.println(x + " is > 5");
} else if (x == 5) {
System.out.println(x + " equals 5");
} else {
System.out.println(x + " is < 5");
}
}
public static void main(String[] arguments) {
test(6);
test(5);
test(4);
}
Questions?
Assignment: FooCorporation
Method to print pay based on base pay and
hours worked
Overtime: More than 40 hours, paid 1.5 times
base pay
Minimum Wage: $8.00/hour
Maximum Work: 60 hours a week
Reminder
•	 Write your own code
•	 Homework due tomorrow (Wednesday)
3pm on Stellar.
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
a == b will return FALSE!
MIT OpenCourseWare
http://ocw.mit.edu
6.092 Introduction to Programming in Java
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More Related Content

Similar to LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf

About java
About javaAbout java
About java
Jay Xu
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Ayes Chinmay
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
Alex Tumanoff
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
Jussi Pohjolainen
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
Shahriar Robbani
 
class object.pptx
class object.pptxclass object.pptx
class object.pptx
Killmekhilati
 
Core java Essentials
Core java EssentialsCore java Essentials
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
ICADCMLTPC
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
Mahyuddin8
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6
Microsoft
 
Java practical
Java practicalJava practical
Java practical
william otto
 

Similar to LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf (20)

About java
About javaAbout java
About java
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
class object.pptx
class object.pptxclass object.pptx
class object.pptx
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6
 
Java practical
Java practicalJava practical
Java practical
 

Recently uploaded

CANSA support - Caring for Cancer Patients' Caregivers
CANSA support - Caring for Cancer Patients' CaregiversCANSA support - Caring for Cancer Patients' Caregivers
CANSA support - Caring for Cancer Patients' Caregivers
CANSA The Cancer Association of South Africa
 
Vicarious movements or trick movements_AB.pdf
Vicarious movements or trick movements_AB.pdfVicarious movements or trick movements_AB.pdf
Vicarious movements or trick movements_AB.pdf
Arunima620542
 
DELIRIUM BY DR JAGMOHAN PRAJAPATI.......
DELIRIUM BY DR JAGMOHAN PRAJAPATI.......DELIRIUM BY DR JAGMOHAN PRAJAPATI.......
DELIRIUM BY DR JAGMOHAN PRAJAPATI.......
DR Jag Mohan Prajapati
 
Champions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdf
Champions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdfChampions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdf
Champions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdf
eurohealthleaders
 
Feeding plate for a newborn with Cleft Palate.pptx
Feeding plate for a newborn with Cleft Palate.pptxFeeding plate for a newborn with Cleft Palate.pptx
Feeding plate for a newborn with Cleft Palate.pptx
SatvikaPrasad
 
Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...
Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...
Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...
nirahealhty
 
NKTI Annual Report - Annual Report FY 2022
NKTI Annual Report - Annual Report FY 2022NKTI Annual Report - Annual Report FY 2022
NKTI Annual Report - Annual Report FY 2022
nktiacc3
 
Pediatric Emergency Care for Children | Apollo Hospital
Pediatric Emergency Care for Children | Apollo HospitalPediatric Emergency Care for Children | Apollo Hospital
Pediatric Emergency Care for Children | Apollo Hospital
Apollo 24/7 Adult & Paediatric Emergency Services
 
CCSN_June_06 2024_jones. Cancer Rehabpptx
CCSN_June_06 2024_jones. Cancer RehabpptxCCSN_June_06 2024_jones. Cancer Rehabpptx
CCSN_June_06 2024_jones. Cancer Rehabpptx
Canadian Cancer Survivor Network
 
Under Pressure : Kenneth Kruk's Strategy
Under Pressure : Kenneth Kruk's StrategyUnder Pressure : Kenneth Kruk's Strategy
Under Pressure : Kenneth Kruk's Strategy
Kenneth Kruk
 
Bringing AI into a Mid-Sized Company: A structured Approach
Bringing AI into a Mid-Sized Company: A structured ApproachBringing AI into a Mid-Sized Company: A structured Approach
Bringing AI into a Mid-Sized Company: A structured Approach
Brian Frerichs
 
Dr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in Cardiology
Dr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in CardiologyDr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in Cardiology
Dr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in Cardiology
R3 Stem Cell
 
PET CT beginners Guide covers some of the underrepresented topics in PET CT
PET CT  beginners Guide  covers some of the underrepresented topics  in PET CTPET CT  beginners Guide  covers some of the underrepresented topics  in PET CT
PET CT beginners Guide covers some of the underrepresented topics in PET CT
MiadAlsulami
 
DRAFT Ventilator Rapid Reference version 2.4.pdf
DRAFT Ventilator Rapid Reference  version  2.4.pdfDRAFT Ventilator Rapid Reference  version  2.4.pdf
DRAFT Ventilator Rapid Reference version 2.4.pdf
Robert Cole
 
Stem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac Care
Stem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac CareStem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac Care
Stem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac Care
Dr. David Greene Arizona
 
Gemma Wean- Nutritional solution for Artemia
Gemma Wean- Nutritional solution for ArtemiaGemma Wean- Nutritional solution for Artemia
Gemma Wean- Nutritional solution for Artemia
smuskaan0008
 
Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)
Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)
Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)
bkling
 
RECENT ADVANCES IN BREAST CANCER RADIOTHERAPY
RECENT ADVANCES IN BREAST CANCER RADIOTHERAPYRECENT ADVANCES IN BREAST CANCER RADIOTHERAPY
RECENT ADVANCES IN BREAST CANCER RADIOTHERAPY
Isha Jaiswal
 
Empowering ACOs: Leveraging Quality Management Tools for MIPS and Beyond
Empowering ACOs: Leveraging Quality Management Tools for MIPS and BeyondEmpowering ACOs: Leveraging Quality Management Tools for MIPS and Beyond
Empowering ACOs: Leveraging Quality Management Tools for MIPS and Beyond
Health Catalyst
 
NEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSON
NEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSONNEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSON
NEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSON
SHAMIN EABENSON
 

Recently uploaded (20)

CANSA support - Caring for Cancer Patients' Caregivers
CANSA support - Caring for Cancer Patients' CaregiversCANSA support - Caring for Cancer Patients' Caregivers
CANSA support - Caring for Cancer Patients' Caregivers
 
Vicarious movements or trick movements_AB.pdf
Vicarious movements or trick movements_AB.pdfVicarious movements or trick movements_AB.pdf
Vicarious movements or trick movements_AB.pdf
 
DELIRIUM BY DR JAGMOHAN PRAJAPATI.......
DELIRIUM BY DR JAGMOHAN PRAJAPATI.......DELIRIUM BY DR JAGMOHAN PRAJAPATI.......
DELIRIUM BY DR JAGMOHAN PRAJAPATI.......
 
Champions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdf
Champions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdfChampions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdf
Champions of Health Spotlight On Leaders Shaping Germany's Healthcare.pdf
 
Feeding plate for a newborn with Cleft Palate.pptx
Feeding plate for a newborn with Cleft Palate.pptxFeeding plate for a newborn with Cleft Palate.pptx
Feeding plate for a newborn with Cleft Palate.pptx
 
Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...
Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...
Can coffee help me lose weight? Yes, 25,422 users in the USA use it for that ...
 
NKTI Annual Report - Annual Report FY 2022
NKTI Annual Report - Annual Report FY 2022NKTI Annual Report - Annual Report FY 2022
NKTI Annual Report - Annual Report FY 2022
 
Pediatric Emergency Care for Children | Apollo Hospital
Pediatric Emergency Care for Children | Apollo HospitalPediatric Emergency Care for Children | Apollo Hospital
Pediatric Emergency Care for Children | Apollo Hospital
 
CCSN_June_06 2024_jones. Cancer Rehabpptx
CCSN_June_06 2024_jones. Cancer RehabpptxCCSN_June_06 2024_jones. Cancer Rehabpptx
CCSN_June_06 2024_jones. Cancer Rehabpptx
 
Under Pressure : Kenneth Kruk's Strategy
Under Pressure : Kenneth Kruk's StrategyUnder Pressure : Kenneth Kruk's Strategy
Under Pressure : Kenneth Kruk's Strategy
 
Bringing AI into a Mid-Sized Company: A structured Approach
Bringing AI into a Mid-Sized Company: A structured ApproachBringing AI into a Mid-Sized Company: A structured Approach
Bringing AI into a Mid-Sized Company: A structured Approach
 
Dr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in Cardiology
Dr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in CardiologyDr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in Cardiology
Dr. David Greene R3 stem cell Breakthroughs: Stem Cell Therapy in Cardiology
 
PET CT beginners Guide covers some of the underrepresented topics in PET CT
PET CT  beginners Guide  covers some of the underrepresented topics  in PET CTPET CT  beginners Guide  covers some of the underrepresented topics  in PET CT
PET CT beginners Guide covers some of the underrepresented topics in PET CT
 
DRAFT Ventilator Rapid Reference version 2.4.pdf
DRAFT Ventilator Rapid Reference  version  2.4.pdfDRAFT Ventilator Rapid Reference  version  2.4.pdf
DRAFT Ventilator Rapid Reference version 2.4.pdf
 
Stem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac Care
Stem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac CareStem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac Care
Stem Cell Solutions: Dr. David Greene's Path to Non-Surgical Cardiac Care
 
Gemma Wean- Nutritional solution for Artemia
Gemma Wean- Nutritional solution for ArtemiaGemma Wean- Nutritional solution for Artemia
Gemma Wean- Nutritional solution for Artemia
 
Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)
Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)
Let's Talk About It: Breast Cancer (What is Mindset and Does it Really Matter?)
 
RECENT ADVANCES IN BREAST CANCER RADIOTHERAPY
RECENT ADVANCES IN BREAST CANCER RADIOTHERAPYRECENT ADVANCES IN BREAST CANCER RADIOTHERAPY
RECENT ADVANCES IN BREAST CANCER RADIOTHERAPY
 
Empowering ACOs: Leveraging Quality Management Tools for MIPS and Beyond
Empowering ACOs: Leveraging Quality Management Tools for MIPS and BeyondEmpowering ACOs: Leveraging Quality Management Tools for MIPS and Beyond
Empowering ACOs: Leveraging Quality Management Tools for MIPS and Beyond
 
NEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSON
NEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSONNEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSON
NEEDLE STICK INJURY - JOURNAL CLUB PRESENTATION - DR SHAMIN EABENSON
 

LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf

  • 1. 6.092: Intro to Java 2: More types, Methods, Conditionals
  • 2. Outline • Lecture 1 Review • More types • Methods • Conditionals
  • 3. Types Kinds of values that can be stored and manipulated. boolean: Truth value (true or false). int: Integer (0, 1, -47). double: Real number (3.14, 1.0, -2.1). String: Text (“hello”, “example”).
  • 4. Variables Named location that stores a value Example: String a = “a”; String b = “letter b”; a = “letter a”; String c = a + “ and “ + b;
  • 5. Operators Symbols that perform simple computations Assignment: = Addition: + Subtraction: ­ Multiplication: * Division: /
  • 6. class GravityCalculator { public static void main(String[] args) { double gravity = -9.81; double initialVelocity = 0.0; double fallingTime = 10.0; double initialPosition = 0.0; double finalPosition = .5 * gravity * fallingTime * fallingTime; finalPosition = finalPosition + initialVelocity * fallingTime; finalPosition = finalPosition + initialPosition; System.out.println("An object's position after " + fallingTime + " seconds is " + finalPosition + “ m."); } }
  • 7. finalPosition = finalPosition + initialVelocity * fallingTime; finalPosition = finalPosition + initialPosition; OR finalPosition += initialVelocity * fallingTime; finalPosition += initialPosition;
  • 9. Outline • Lecture 1 Review • More types • Methods • Conditionals
  • 10. Division Division (“/”) operates differently on integers and on doubles! Example: double a = 5.0/2.0; // a = 2.5 int b = 4/2; // b = 2 int c = 5/2; // c = 2 double d = 5/2; // d = 2.0
  • 11. Order of Operations Precedence like math, left to right Right hand side of = evaluated first Parenthesis increase precedence double x = 3 / 2 + 1; // x = 2.0 double y = 3 / (2 + 1); // y = 1.0
  • 12. Mismatched Types Java verifies that types always match: String five = 5; // ERROR! test.java.2: incompatible types found: int required: java.lang.String String five = 5;
  • 13. Conversion by casting int a = 2; // a = 2 double a = 2; // a = 2.0 (Implicit) int a = 18.7; // ERROR int a = (int)18.7; // a = 18 double a = 2/3; // a = 0.0 double a = (double)2/3; // a = 0.6666…
  • 14. Outline • Lecture 1 Review • More types • Methods • Conditionals
  • 15. Methods { } public static void main(String[] arguments) System.out.println(“hi”);
  • 16. Adding Methods public static void NAME() { STATEMENTS } To call a method: NAME();
  • 17. class NewLine { public static void newLine() { System.out.println(""); } public static void threeLines() { newLine(); newLine(); newLine(); } public static void main(String[] arguments) { System.out.println("Line 1"); threeLines(); System.out.println("Line 2"); } }
  • 18. class NewLine { public static void newLine() { System.out.println(""); } public static void main(String[] arguments) { System.out.println("Line 1"); threeLines(); System.out.println("Line 2"); public static void threeLines() { newLine(); newLine(); newLine(); } } }
  • 19. public static void main(String[] arguments) { System.out.println("Line 1"); threeLines(); System.out.println("Line 2"); public static void threeLines() { newLine(); newLine(); newLine(); } class NewLine { public static void "" newLine() { System.out.println( ); } } }
  • 20. Parameters public static void NAME(TYPE NAME) { STATEMENTS } To call: NAME(EXPRESSION);
  • 21. class Square { public static void printSquare(int x) { System.out.println(x*x); } public static void main(String[] arguments) { int value = 2; printSquare(value); printSquare(3); printSquare(value*2); } }
  • 22. class Square2 { public static void printSquare(int x) { System.out.println(x*x); } public static void main(String[] arguments) { printSquare("hello"); printSquare(5.5); } } What’s wrong here?
  • 23. class Square3 { public static void printSquare(double x) { System.out.println(x*x); } public static void main(String[] arguments) { printSquare(5); } } What’s wrong here?
  • 24. Multiple Parameters […] NAME(TYPE NAME, TYPE NAME) { STATEMENTS } To call: NAME(arg1, arg2);
  • 25. class Multiply { public static void times (double a, double b) { System.out.println(a * b); } public static void main(String[] arguments) { times (2, 2); times (3, 4); } }
  • 26. Return Values public static TYPE NAME() { STATEMENTS return EXPRESSION; } void means “no type”
  • 27. class Square3 { public static void printSquare(double x) { System.out.println(x*x); } public static void main(String[] arguments) { printSquare(5); } }
  • 28. class Square4 { public static double square(double x) { return x*x; } public static void main(String[] arguments) { System.out.println(square(5)); System.out.println(square(2)); } }
  • 29. Variable Scope Variables live in the block ({}) where they are defined (scope) Method parameters are like defining a new variable in the method
  • 30. class SquareChange { public static void printSquare(int x) { System.out.println("printSquare x = " + x); x = x * x; System.out.println("printSquare x = " + x); } public static void main(String[] arguments) { int x = 5; System.out.println("main x = " + x); printSquare(x); System.out.println("main x = " + x); } }
  • 31. class Scope { public static void main(String[] arguments) { int x = 5; if (x == 5) { int x = 6; int y = 72; System.out.println("x = " + x + " y = " + y); } System.out.println("x = " + x + " y = " + y); } }
  • 32. Methods: Building Blocks • Big programs are built out of small methods • Methods can be individually developed, tested and reused • User of method does not need to know how it works • In Computer Science, this is called “abstraction”
  • 33. Mathematical Functions Math.sin(x) Math.cos(Math.PI / 2) Math.pow(2, 3) Math.log(Math.log(x + y))
  • 34. Outline • Lecture 1 Review • More types • Methods • Conditionals
  • 35. if statement if (CONDITION) { STATEMENTS }
  • 36. public static void test(int x) { if (x > 5) { System.out.println(x + " is > 5"); } } public static void main(String[] arguments) { test(6); test(5); test(4); }
  • 37. Comparison operators x > y: x is greater than y x < y: x is less than y x >= y: x is greater than or equal to x x <= y: x is less than or equal to y x == y: x equals y ( equality: ==, assignment: = )
  • 38. Boolean operators &&: logical AND ||: logical OR if ( x > 6 && x < 9) { if (x > 6) { … if (x < 9) { } … } }
  • 39. else if (CONDITION) { STATEMENTS } else { STATEMENTS }
  • 40. public static void test(int x) { if (x > 5) { System.out.println(x + " is > 5"); } else { System.out.println(x + " is not > 5"); } } public static void main(String[] arguments) { test(6); test(5); test(4); }
  • 41. else if if (CONDITION) { STATEMENTS } else if (CONDITION) { STATEMENTS } else if (CONDITION) { STATEMENTS } else { STATEMENTS }
  • 42. public static void test(int x) { if (x > 5) { System.out.println(x + " is > 5"); } else if (x == 5) { System.out.println(x + " equals 5"); } else { System.out.println(x + " is < 5"); } } public static void main(String[] arguments) { test(6); test(5); test(4); }
  • 44. Assignment: FooCorporation Method to print pay based on base pay and hours worked Overtime: More than 40 hours, paid 1.5 times base pay Minimum Wage: $8.00/hour Maximum Work: 60 hours a week
  • 45. Reminder • Write your own code • Homework due tomorrow (Wednesday) 3pm on Stellar.
  • 46. 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”);
  • 47. Comparison operators • Do NOT call == on doubles! EVER. double a = Math.cos (Math.PI / 2); double b = 0.0; a = 6.123233995736766E-17 a == b will return FALSE!
  • 48. MIT OpenCourseWare http://ocw.mit.edu 6.092 Introduction to Programming in Java January (IAP) 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.