Intro to Java Midterm Review Dan Deutsch Daniel Deutsch.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter2: Introduction to Java Applications 1.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
CMT Programming Software Applications
Some basic I/O.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Hello, world! Dissect HelloWorld.java Compile it Run it.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Java. Main() Main method is where the program execution begins. There is only one main Displaying the results: System.out.println (“Hi.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Chapter 2: Java Fundamentals
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Introduction to Java Java Translation Program Structure
Primitive Data Types. Identifiers What word does it sound like?
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Chapter 2 Variables.
Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
By Mr. Muhammad Pervez Akhtar
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS 106 Introduction to Computer Science I 01 / 24 / 2007 Instructor: Michael Eckmann.
Review for exam 1 CS 101 Aaron Bloomfield. 2 Today’s lecture An overview of the “review” sections of chapters 1- 3 and 5 Stop me if you want me to go.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CompSci 230 S Programming Techniques
4. Java language basics: Function
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Yanal Alahmad Java Workshop Yanal Alahmad
Lecture 2: Data Types, Variables, Operators, and Expressions
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Java Programming: From Problem Analysis to Program Design, 4e
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Starting JavaProgramming
An Introduction to Java – Part I, language basics
MSIS 655 Advanced Business Applications Programming
Review for Exam 1 Spring 2007 CS 101/CS 101-E.
Fundamentals 2.
elementary programming
Introduction to Java Applications
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Unit 3: Variables in Java
Presentation transcript:

Intro to Java Midterm Review Dan Deutsch Daniel Deutsch

About Java Compiled vs. Interpreted Java is compiled to Java Bytecode, not interpreted Bytecode is then interpreted when the program runs Python is interpreted, so it translates as the program runs on the computer The Java API The Java Application Programming Interface is a library of code that you can use in Java programs It has things like the String class and the Scanner class Daniel Deutsch

Primitives and Reserved Words Primitives Types already built into Java. Variables can be these types They turn purple in jGrasp Integer types: byte, short, int, long Floating point types: float, double Other: boolean, char Reserved words You can’t use any of the words that Java has reserved to be “keywords” as a variable name All of the primitives, public, private, protected, static, void, class, switch, case, default, for, while, do, continue, if, else, return, new, this, throw, throws, Daniel Deutsch

Variable Names Variables must start with a letter, underscore or $ After the first letter, it can be a letter, an underscore, $ or a number Good examples: Num1, DAYS_IN_YEAR, $, money$$, _scanner Bad examples: 7even, hello world, private, num1* Daniel Deutsch

Characters Stored in memory as 8 bits Indicated by single quotes Each character maps to a number between 0 and 255 ‘a’ = 97 ‘A’ = 65 ‘0’ = 48 This means that ‘a’ > ‘A’ char c1 = ‘a’; System.out.println(c1 + 2); int c2 = c1 + 2; System.out.println(c2); char c3 = (char) (c1 + 2); System.out.println(c3); 99 c Daniel Deutsch

Arithmetic Operators have an order of operations () - negation *, /, % +, - = Be careful of integer division!! Casting helps to get around this int a = 5, b = 2; System.out.println(a / b); System.out.println((double) a / b); double c = 5.0; System.out.println(c / b); System.out.println(5.0 / b); double d = 8.825; int e = (int) d; System.out.println(e); System.out.println((double) (5 / 2)); Daniel Deutsch

Arithmetic The mod operator % gives you the remainder when dividing two numbers int mod = 33 % 4; Find the ones digit of the number 2358? int ones = 2358 % 10; The tens digit? int tens = 2358 / 10; tens = tens % 10; Misc. operators num++, num += 1, num = num + 1 What’s the difference between num++ and ++num ? num++ executes then line, then increments by 1 ++num increments by 1, then executes line int num = 0; System.out.println(num++); // num is now 1 System.out.println(++num); , *=, /=, +=, -=, %= Daniel Deutsch

Objects Objects are instantiations of Classes They have data associated with them and you can call methods on them Scanner scanner = new Scanner(“Dan 37.4 java”); // here we call the next() method on a scanner String d = scanner.next(); Java saves the location in memory where the Object’s data is. Primitives actually save the value of the variable int a = 5; String s = “Dan”; The Math class and the Character class provide static methods that you can call with the class name double d = Math.floor(3.25); You cannot instantiate them! Math math = new Math(); a 5 s Dan 3.0 Daniel Deutsch

Strings Strings are Objects, not primitive types Indicated with double quotes Length String s = “abcdefghijk”; int length = s.length(); indexOf int index = s.indexOf(‘c’); char bad = s.charAt(length); charAt char c = s.charAt(index); substring String s1 = s.substring(3); String s2 = s.substring(index, 6); 11 2 Crashes! c defghijk cdef toLowerCase String lower = “UPPER”.toLowerCase(); toUpperCase upper Daniel Deutsch

Strings Escape characters There are special characters which use two symbols to represent them \t is a tab \n is a newline character \\ is the \ character String s = “1\t2\n\t3\t\\”; System.out.println(s); 123\123\ Daniel Deutsch

Strings Covert a String to an int or double String s = “72”; int a = Integer.parseInt(s); double d = Double.parseDouble(“38.08”); int b = Integer.parseInt(“seven”); Convert a number into a String int a = 7; String s = a + “”; If you need to compare two String s, never use ==. The == operator compares the values at the memory address. Objects store a location in memory where the data is stored, not the actual value of the variable. Use equals instead String s1 = “Java”, s2 = “Java”; if (s1.equals(s2)) System.out.println(“same!”); equalsIgnoreCase() Crashes! Daniel Deutsch

Scanner Scanner is a class that allows you to iterate over a stream of text, like System.in or a String It’s located in java.util.Scanner, which you have to import initialization Scanner kb = new Scanner(System.in); Scanner s = new Scanner(“Dan ”); hasNext hasNextLine next if (scanner.hasNext()) String d = s.next(); nextInt int a = s.nextInt(); nextDouble double d = s.nextDouble(); nextChar does not exist. Do this instead: // user types “yes” char c = kb.next().charAt(0); true “Dan” s.next(); s.hasNext(); ‘y’ Crashes! false Daniel Deutsch

Scanner Example “First Last” Scanner s = new Scanner(“First Last”); s.next(); s.nextInt(); s.nextDouble(); s.nextInt(); s.next(); “First” “3” crashes! Last s.hasNext(); false Daniel Deutsch

Math Class You can use the Math class to do useful math operations You call the methods with the Math class pow double d1 = Math.pow(2, 3); round double d2 = Math.round(7.8); ceil double d3 = Math.ceil(2.1); double d4 = Math.ceil(3.0); floor double d5 = Math.floor(5.6); sqrt double d6 = Math.sqrt(34); … Daniel Deutsch

Printf The printf command allows you to format a print statement in very specific ways You create a String that encodes the output format of the string %d for integers %f for floats %s for Objects (e.g. Strings ) % displays %, like the \ character works with normal Strings You can specify how many spaces wide you want the result to be and how many points after the decimal you want to see %.2f will have 2 digits after the decimal, padded with 0s. Dosen’t work with integers – why? %8d will make sure the width of the number is at least 8 characters %08d will pad the number with 0s if necessary The newline character \n is not included, like System.out.print(); Daniel Deutsch

Printf Examples int a = 7; System.out.printf(“%3d\n”, a); System.out.printf(“%03d\n”, a); double d = 3.2; System.out.printf(“%04d\n”, d); System.out.printf(“%.3f\n”, d); System.out.printf(“%06.3f%\n”, d); System.out.printf(“My name is %s\n”, “Dan”); double d2 = ; System.out.printf(“%f\n”, d2); System.out.printf(“%2f\n”, d2); “ 7” “007” crashes! “3.200” “03.200%” “My name is Dan” Daniel Deutsch

If Statements If statements are useful when you want to change the logic of your program based on values of variables or properties of Objects They must use expressions that evaluates to Booleans If true, it will only execute the next statement unless curly braces are used to create code blocks, regardless of indentation if (a == 3) System.out.println(“equal”); System.out.println(“always runs”); a = 3; “equals” “always runs” a = 2; “always runs”; If statements can combine with else statements for more control. If the if statement evaluates to false, the else statement runs. Otherwise only the if statement runs if (a == 3) System.out.println(“equal”); else System.out.println(“not equal”); a = 3 a = 2 Daniel Deutsch

If Statements If you have mutually exclusive options, you can use an if-else-if structure. If you include an else, exactly one of the options will be chosen char choice = kb.next().charAt(0); if (choice = ‘a’) System.out.println(“a chosen”); else if (choice == ‘b’) System.out.println(“b chosen”); char choice = kb.next().charAt(0); if (choice = ‘a’) System.out.println(“a chosen”); else if (choice == ‘b’) System.out.println(“b chosen”); else System.out.println(“neither”); ab c a b c Daniel Deutsch

If Statement Examples int a = 2, b = 3; if (a == 2 && b == 3) System.out.println(1); else if (!(a != 2 || b != 3)) System.out.println(2); 1 This will never be called, no matter what a and b are. Why? (a == 2 && b == 3) is the same as !(a != 2 || b != 3) if (a == 8 && b == 5) System.out.println(“a is 8”); System.out.println(“b is 5”); Misleading indentation! Only executes next statement! a = 2, b = 3 if (a == 8 && b == 5) x++; y++; a = 8, b = 5 if (a == 8 && b == 5) { System.out.println(“a is 8”); System.out.println(“b is 5”); } a = 2, b = 3 a = 8, b = 5 a = 2, b = 3 Daniel Deutsch

If Statement Examples if (a <= 5) if (b <= 2) Sysytem.out.println(“tiny”); else { System.out.println(“huge”); System.out.println(“end”); } Misleading indentation! Rewrite it if (a <= 5) if (b <= 2) System.out.println(“tiny”); else { System.out.println(“huge”); System.out.println(“end”); } else goes with the most recent if a = 2, b = 1 a = 2, b = 3 a = 6, b = 1 if (a <= 5) { if (b <= 2) System.out.println(“tiny”); } else System.out.println(“huge”); System.out.println(“end”); { } This is the same thing! Just clearer (and better) if (a <= 5) { if (b <= 2) System.out.println(“tiny”); } else System.out.println(“huge”); System.out.println(“end”); Misleading indentation! Rewrite it a = 2, b = 1 a = 2, b = 5 a = 6, b = 1 Daniel Deutsch

Switch Statements Switch statements are interesting control structures. They are like if statements, but multiple clauses can be executed Unless there is a break, the program will keep executing The default case is for when no other case is selected char choice = kb.next().charAt(0); switch (choice) { case ‘a’: case ‘A’: x++; break; case ‘b’: y++; default: z++; } a a a a a a A A A A A A b b b b b b b c c c c c c c Daniel Deutsch

For Loops For loops are useful when code needs to be repeated and you know how many times it needs to execute. You may not know it will execute 5 times every time the code runs, but it will execute s.length() times There are 3 parts that create the for loop They are executed in the following order: 1. Initialization 2. condition 2.1 If true, the body 2.2 Otherwise, end 3. Afterthought 4. Go to step 2 for (int i = 0; i < s.length(); i++) initialization condition afterthought Daniel Deutsch

For Loop Examples for (int i = 0; i < 10; i++) System.out.print(i + “ “); String s = “I love Java”; for (int i = 0; i < s.length(); i += 2) System.out.print(s.charAt(i)); for (int n = 1; n < 1000; n *= 2) System.out.print(n + “ “); for (int i = 10; i 0; i--) System.out.print(i + “ “); for (int i = 0; i < 10; i++) System.out.println((i * 2) + “ “); System.out.println(“finished body”); Nothing! … 18 Finished body { } 0 Finished body 2 Finished body 4 … 18 Finished body … 1 < > 01 2 … 9 i = I lv a a n = 1 1 * 2 2 2* * … 512 Daniel Deutsch

While and Do-While Loops While loops are useful when you don’t know how many times the loop will run. Could be based on user input Do-while loops are useful when you don’t know how many times it will run, but it will run at least once int num = 0; while (num < 5) { if (kb.next().equals(“y”)) num++; } do { char choice = kb.next().charAt(0); // display menu } while (choice != ‘q’); Daniel Deutsch

File Structure The class declaration goes first Method declarations of the class go in the body Any imports/package declarations go outside of the class public class MyClass { } public static void main(String[] args) { } // code goes here public static int add(a, int b) { return a + b; } class declaration Memorize this! main method other methods import java.util.Scanner; imports Daniel Deutsch

Testing White box testing: every line of code get executed. The white box means you can see the code and make the test cases based on the code Test boundary cases Test invalid and valid cases Regression testing: rewriting code or adding code and making sure that everything that worked before works now Black box testing: try many values that are valid/invalid. You don’t know what the program is doing, so you try many cases if (0 <= a && a <= 10) Test -1, 0, 1, 9, 10, and 11. Probably values in between Daniel Deutsch