lec7
UCSD, CSE 8
Excerpt: ... h variable, labelled with the identifier that names the variable Write the variable's value in its box (use a literal constant appropriate to the type of the variable, don't bother with writing individual bits!) Let's look at some examples, to help understand what happens when primitive type values are passed by value. CSE 8A, UCSD LEC7 Page 8 of 31 Arguments passed by value public class Test { static void foo(int a) / when foo is called, value of actual / argument is assigned to / the formal argument a { a = a + 1; / value of a is increased by 1 System.out.println(a); / prints out value of a } public static void main(String args[]) { int b = 3; / creates an int variable named b with value 3 foo(b); / calls function foo, passing the value of / the actual argument b System.out.println(b); } / prints out value of b, which is. CSE 8A, UCSD LEC7 Page 9 of 31 Arguments passed by value: picturing variables, frame 1 public class Test { static void foo(int a) { ...
|
|
02-ch01-2-methods
Washington, CSE 142
Excerpt: ... tured: 1. Make the cookie batter. 2a. Bake the first batch of cookies. 2b. Bake the second batch of cookies. 3. Add frosting and sprinkles. Observations about the structured algorithm: It is hierarchical, therefore easier to understand. Higher-level operations help eliminate redundancy. Copyright 2006 by Pearson Education 6 A program with redundancy redundancy: Occurrence of the same sequence of commands multiple times in a program. public class TwoMessages { public static void main(String[] args) { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); System.out.println(); System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); } } Output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down We print the same m ...
|
|
quiz2
Concordia Chicago, CSPP 51036
Excerpt: ... N) - 11. Do all interfaces implicitly extend Object? (Y or N) - 12. Can an interface implement another interface? (Y or N) - 13-14. Can an object be upcast to a variable of type interface . - if the object implements the interface? (Y or N) - if the object does not implement the interface? (Y or N) - Study the following code carefully. Note that there are three files - Robbery.java, Account.java and CheckingAccount.java. The latter two are in their own package. /in Robbery.java import bank.CheckingAccount; import bank.Account; public class Robbery{ public static void main(String[] args){ CheckingAccount acc1 = new CheckingAccount(); MiscreantAccount acc2 = new MiscreantAccount(); acc2.steal(acc1); } } class MiscreantAccount extends Account{ void steal(CheckingAccount acc){ acc.balance -= 100.; } } /in bank/Account.ja ...
|
|
05-ch02-3-loopfigures
Washington, CSE 142
Excerpt: ... e need on each line output? Which loops are nested inside which other loops? How should we use static methods to represent the structure and redundancy of the output? of the top half of the Copyright 2006 by Pearson Education #=# | <><> | | <>.<> | | <>.<> | |<>.<>| |<>.<>| | <>.<> | | <>.<> | | <><> | #=#9 Partial solution / Prints the expanding pattern of <> for the top half of the figure. public static void drawTopHalf() { for (int line = 1; line <= 4; line+) { System.out.print("|"); for (int space = 1; space <= (line * -2 + 8); space+) { System.out.print(" "); } System.out.print("<>"); for (int dot = 1; dot <= (line * 4 - 4); dot+) { System.out.print("."); } System.out.print("<>"); for (int space = 1; space <= (line * -2 + 8); space+) { System.out.print(" "); } System.out.println("|"); } } Copyright 2006 by Pearson Education 10 Scope and class constants reading: 2.4 Copyright 2006 by Pearson E ...
|
|
lecture
University of Florida , CGS 2414
Excerpt: ... = CGS 2414 Lecture 14 ep@cise.ufl.edu = For Loops Another type of loop, the for statement is the most powerful and complicated It is ideal for counting loops and sequential access of array data Syntax for ( initialization; controlling expression; update expression ) statement In some cases, a while and for loop behave exactly the same initialization; while ( controlling expression ) { statement; update expression; } Initialization: performed only once - before the loop begins to execute Controlling expression: evaluated everytime to control whether the loop is executed Update expression: performed everytime after the loop is executed = Tracing Execution public class loop { public static void main(String [] args) { int[] num_array = { 4 ...
|
|
recursion
NYU, CS 22
Excerpt: ... For today, we will focus on the basic structure of using recursive methods. Worlds Simplest Recursion Program Worlds Simplest Recursion Program public class Recursion { public static void main (String args[]) { count(0); This program simply counts System.out.println(); from 0-2: } public static void count (int index) { System.out.print(index); if (index < 2) count(index+1); } } 012 This is where the recursion occurs. calls itself. You can see that the count() function Visualizing Recursion To understand how recursion works, it helps to visualize whats going on. To help visualize, we will use a common concept called the Stack. A stack basically operates like a container of trays in a cafeteria. It has only two operations: Push: you can push something onto the stack. Pop: you can pop something off the top of the stack. Lets see an example stack in action. Stacks The diagram below shows a stack over time. We perform two pushes and one pop. 8 2 Time: 0 Time 1: ...
|
|
lecture8-2005
East Los Angeles College, CS 118
Excerpt: ... oximately 10-15 minutes Take note of the surname order, e.g. 1 2 11.30-12.30 1 Jhutti Lu Friday 4-5pm CS1.01 (CS) Andrew 4.30-5.30 Mandeep Jhutti come at 11.30; Stuart Knight come at 11.40; Wei Lu come at 11.50 CS118: Programming for Computer Scientists 1 CS118: Programming for Computer Scientists 2 Last lecture Introduced environment diagrams This was a graphical way of viewing and reasoning about the program state Properties of environment diagrams included They contained definitions of variables, methods and the imported class definitions Iteration (loops) and calls to methods cause new environments to be created Scope The scope of an identifier is the portion of the program in which the identifier can be referenced public class Test { public static void main (String [ ] args) { int x = IO.readint(How many stars?); A (x); od } eth public static void A (int n) ble aria { of v ope i <= n; i+) star(); for (int i = 1; e sc } is th public static void star () { System.out.println( ...
|
|
Exceptions
Oakland University, L 230
Excerpt: ... Exceptions 1 Out of Bounds Java checks the bounds of arrays. class ArrayOutOfBounds { public static void main( String args[] ) { int students[] = new int[5]; students[ 10 ] = 1; System.out.println( " The End" ); } } Output java.lang.ArrayIndexOutOfBoundsException: 10 at ArrayOutofBounds.main(All.java:8) 2 Exception Handling There are events which may be considered exceptional or unusual Error conditions: On zero divide have the program do some recovery process or give some debugging information. Special conditions: If a plane is to collide with another the navigation program should perform some special operation. 3 Detecting exceptions Boolean foo( ) { Boolean zeroDivideFlag = false; if ( A * A - 2 * B = 0 ) zeroDivideFlag = true; else result = sqrt( C )/ ( A * A - 2 * B ); return zeroDivideFlag; } / in main flag = foo( ); if ( flag = true ) / now what? 4 Definitions Exception A condition that is detected by an operation, that cannot be resolved within the local context of the operation, ...
|
|
Hanoi.java
Harvard, LIBE 50
Excerpt: ... /* Hanoi.java * unit 5 lecture notes * Solve "Towers of Hanoi" puzzle * * @author: Dr. Henry H. Leitner * @version: Last Modified January 2, 2009 */ import java.util.*; class Hanoi { static void towers ( char origin , char dest, char intermed, int numDisks) { if ( numDisks = 1) System.out.println ("Move disk #1 from " + origin + " to " + dest); else { towers ( origin, intermed, dest, numDisks-1 ); System.out.println ("Move disk #" + numDisks + " from " + origin + " to " + dest); towers ( intermed, dest, origin, numDisks-1); } } public static void main (String[] args) { int n; Scanner keyboard = new Scanner (System.in); System.out.print ("How many disks you wanna play with? "); n = keyboard.nextInt(); towers( 'S', 'D', 'I', n); } } ...
|
|
Lect25Feb
University of Texas, CS 313
Excerpt: ... Lecture Notes on 25 Feb 2009 * Exception Handling * Throwing and Catching public class SomeClass { public int div (int a, int b) throws ArithmeticException { if ( b = 0 ) throw new ArithmeticException ( "ERROR: Division by Zero" ); return a / b; } } public class Driver { public static void main (String[] args) { try { SomeClass obj = new SomeClass (); int a = 4; int b = 3; System.out.println ( obj.div (a, b) ); } catch ( ArithemeticException e) { System.out.println (e.getMessage(); } } OR public static void main (String[] args) throws ArithmeticException { SomeClass obj = new SomeClass (); int a = 4; int b = 3; System.out.println ( obj.div (a, b) ); } } { try { if ( b = 0 ) throw new ArithmeticException ( "ERROR: Division by Zero" ); return a / b; } catch (ArithmeticException e) { return 0; } } * Exception Hierarchy * Creating & Throw ...
|
|
Exam2StudyGuide
Missouri State, CIS 260
Excerpt: ... /* * Exam2StudyGuide.java * Richard Johnson * 10/22/07 * This program reads data from a file and displays it */ import javax.swing.JOptionPane; import java.util.Scanner; import java.io.File; import java.io.IOException; public class Exam2StudyGuide { public static void main(String[] args) throws IOException { / declare variables String filename, intro = "This program displays the contents of a file", message = "Enter the name of the file (such as data.txt)"; / input JOptionPane.showMessageDialog( null, intro ); filename = JOptionPane.showInputDialog( message ); / Open the file. File file = new File( filename ); Scanner inputFile = new Scanner( file ); / Read lines from the file until no more are left. while ( inputFile.hasNext() ) { / Read the next name. String record = inputFile.nextLine(); / Display the last name read. System.out.println( record ); } System.out.println(); / print a blank line ...
|
|
cs026_2
UWO, CS 026
Excerpt: ... e) then translates and executes the bytecode on the computer, one bytecode instruction at at time. Why does Java do it this way? The Java Language Portability: create compiler once; then create an interpreter for each machine. (An interpreter is easier to create than a compiler . Why?) 31 A Java Program: HelloWorld A first look at the classic introductory example: HelloWorld. All the program does is simply print the text "Hello World!" to the screen. For some reason, this tends to be the first program demonstrated in any program language. 32 /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the screen */ import java.io.*; public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World!"); } } 33 /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the scre ...
|
|
cs026_2
UWO, CS 026
Excerpt: ... Java Program: HelloWorld A first look at the classic introductory example: HelloWorld. All the program does is simply print the text Hello World! to the screen. For some reason, this tends to be the first program demonstrated in any program language. 32 /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the screen */ import java.io.*; public class HelloWorld { public static void main (String[] args) { System.out.println(Hello World!); } } 33 /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the screen */ import java.io.*; public class HelloWorld { public static void main (String[] args) { System.out.println(Hello World!); } } 34 Comments: Indicated by /* */ or / Ignored by the computer For programmers /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see w ...
|
|
cs026_2_2
UWO, CS 026
Excerpt: ... nagement 16 Computer Science 032a/b /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the screen */ import java.io.*; public class HelloWorld { public static void main (String[] args) { System.out.println(Hello World!); } } 33 /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the screen */ import java.io.*; public class HelloWorld { public static void main (String[] args) { System.out.println(Hello World!); } } 34 Comments: Indicated by /* */ or / Ignored by the computer For programmers Database Management 17 Computer Science 032a/b /* HelloWorld.java CS026 Lecture Notes Examples Task: - the classic first program to see when learning a programming language -outputs a message to the screen */ import java.io.*; public class HelloWorld { public static void main (String[] args) { System.out.printl ...
|
|
Tutorial05
FIU, COP 2210
Excerpt: ... Florida International University COP 2210 Tutorial # 5 Name _ Id # _ Sec _ Question 1. Study the following program, in particular the if statements. class Mystry { public static void main(String[] arg) { int i = 10; int j = 12; if (i < j & (i = 30) / 2 > 5) System.out.println(i is + i ); } } (a) On the space provided below, write what you think will result when you attempt to compile the program. _ _ (b) if the program did not compile fix the error(s). Record the correction in the space provided below. _ _ Question 2 Given the following code: class mystry { public static void main(String[] arg) { int i = 10; int j = 12; ...
|
|
mgp00013
University of Florida , CGS 2414
Excerpt: ... Notes about overriding static methods can't be overridden However, a static method can *hide* an inherited static method So if we define this: public class Account { private double balance; . public static void message() { System.out.println("FNB of Guam"); } ...
|
|
oop
Cornell, CS 211
Excerpt: ... logical proofs 2 Implementing puzzle operations scramble: put puzzle into Sam Loyd configuration s = 123456879; Key question in Ur-Java What kind of variable should we use to store the integer that represents puzzle state? 1. method parameter/local variable stack allocation allocated in static area tile (r,c): what is tile in position (r,c)? return (s/108-(3r+c) % 10 2. class variable move: left to reader As we will see, these implementation choices affect the interface of the Puzzle class. Interface L(ocal) (1) state in Ur-Java code: Interface L class testPuzzle { public static void main(String[] args) { int state = Puzzle.scramble(); display(state); state = Puzzle.move(state, N); . } class Puzzle { public static int scramble() { return 123456879; } public static int tile(int state, int r, int c) { return state/(int)Math.pow(10,8-(3*r+c) %10 ; } class TestPuzzle (2) state out class Puzzle State is implemented as local variable in class Test ...
|
|
Lecture 12
Virginia Tech, CS 1054
Excerpt: ... CS1054: Lecture 12 Creating Stand Alone applications Class Methods .aka static Methods This methods use the keyword `static' in the method signature public class Example { public static void myStaticMethod() { . } public void myInstanceMethod() { . } } Usage Example.myStaticMethod(); [ClassName.methodName()] Static Methods Static methods can access only static fields or class variables They cannot access instance fields They can call only other static methods. They cannot call other instance methods (but vice versa is true) The main method An application usually starts without any object in existence. To start a Java Application, we need to use a class method. Thus, user specifies the class that should be started. Java system will then invoke main method in that class. main method public static void main (String args[]) Static => class method Parameters => arguments you want to pass to your program Has to be public! Example ...
|
|
06-ch03-1-parameters
Washington, CSE 142
Excerpt: ... okies: Mix the following ingredients in a bowl: N/5 N/20 N/20 N/10 N/20 . cups flour cups butter cups sugar eggs bags chocolate chips Place on sheet and Bake for about 10 minutes. parameter: A value that distinguishes similar tasks. parameterize: To express a set of similar tasks in a general way in terms of one or more parameters. Copyright 2006 by Pearson Education 5 Redundant figures Consider the task of drawing the following figures: * * * * * * * * * * * * * The lines and figures are similar, but not exactly the same. 6 Copyright 2006 by Pearson Education A redundant solution public class Stars1 { public static void main(String[] args) { drawLineOf13Stars(); drawLineOf7Stars(); drawLineOf35Stars(); draw10x3Box(); draw5x4Box(); } public static void drawLineOf13Stars() { for (int i = 1; i <= 13; i+) { System.out.print("*"); } System.out.println(); } public ...
|
|
lecture
University of Florida , CGS 2414
Excerpt: ... = CGS 2414 Lecture 21 ep@cise.ufl.edu = The "switch" Statement An alternative to cascading if statements public class sw { public static void main(String [] args) { int num = Integer.parseInt(args[0]); if (num = 1) System.out.println("Monday"); else if (num = 2) System.out.println("Tuesday"); else if (num = 3) System.out.println("Wednesday"); else if (num = 4) System.out.println("Thursday"); else if (num = 5) System.out.println("Friday"); else if (num = 6) System.out.println("Saturday"); else if (num = 7) System.out.println("Sunday"); else System.out.println("Invalid day entered"); } } = ...
|
|
lecture10-2005
East Los Angeles College, CS 118
Excerpt: ... Lecture 10 Class test Results available from your seminar tutors Last lecture lecture Procedural Programming Data and operations on the data are separate Seminars This weeks seminars will go through the class test Meet in the classroom (not in the labs) Object Oriented Programming Data and operations are bundled together in a class These classes are blueprints from which we can create objects Justification Allowed related data and operations to be grouped together, provides a better way of structuring large complex code Allowed more complex datatypes to be represented CS118: Programming for Computer Scientists CS118: Programming for Computer Scientists 1 2 Last lecture lecture Creating objects A constructor method determines how objects are created The new operator is used to actually create the object Circle myCircle = new Circle (5.0); class TestCircle { / the main class public static void main(String[] args) { Circle myCircle = new Circle(5.0); System.out.println(Radius + m ...
|
|
javabasics1
Old Dominion, CS 476
Excerpt: ... Java Basics - Part I (lectures programs) Sun OnLine Documentations Chapter 2: Everything is an Object First Example: HelloDate Run as applet public class HelloDate { public static void main(String[] args) { System.out.println("Hello, it's: "); System.out.println(new Date(); } } How to Complie it? % make OR % javac HelloDate.java How to Run it? % java HelloDate Java Documentation: % javadoc HelloDate.java (use netscape to look at the documentation HelloDate.html) Exec Example: Exec This excute any program, e.g.: public class Exec { public static void main(String[] args) { try { String command = args[0]; System.out.println("exec: " + command); Process p = Runtime.getRuntime().exec(command); p.waitFor(); } catch (InterruptedException e){} catch (IOException e){} } } Example: % jave Exec prog Where prog can be: C program prog.c Java program progHelloDate.c shell program prog.Whotty Note that prog.Who produces no output! Chapter 3: Controlling Program Flow operators, pre ...
|
|
lec9
UCSD, CSE 8
Excerpt: ... in e copy value in e, store it in d this makes d and e have the same value for now, but they are still separate variables CSE 8A, UCSD LEC 9 Page 4 of 33 Pointers and objects Consider this program fragment: public static void main(String[] args) { String s; String name; Circle c; PrintWriter pw; Frame myApp; Canvas c1, c2, c3; Integer i; String t; int x,y,z; How many reference variables (pointers) now exist at this point in the program? _ How many objects exist (ignoring args)? _ CSE 8A, UCSD LEC 9 Page 5 of 33 Pointers and objects, cont'd Now consider this different program fragment: public static void main(String[] args) { String s = "123"; String name = s; Circle c = new Circle(); PrintWriter pw; Frame myApp; Canvas c1, c2, c3; Integer i = Integer.valueOf(s); String t = s + name; int x,y,z; How many reference variables (pointers) now exist at this point in the program? _ How many objects exist (ignoring args)? _ Summary: You creat ...
|