JAVA & Computer Science

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Static (shared by all) Variables, Constants and Methods

*A static variable is shared by all objects of the* *class.* *A static method cannot access instance members* *of the class.* If you want all the instances of a class to share data, use static variables, also known as class variables. Static variables store values for the variables in a common memory location. Because of this common location, *if one object changes the* *value of a static variable, all objects of the same* *class are affected.* Static methods can be called without creating an instance of the class. Constants in a class are shared by all objects of the class. Thus, constants should be declared as final static. *final static double PI = 3.14159265358979323846;* How do you decide whether a variable or a method should be an instance one or a static one? A variable or a method that is dependent on a specific instance of the class should be an instance variable or method. The main method is static and can be invoked directly from a class.

aggregation

*Aggregation is a special form of association that* *represents an ownership relationship between* *two objects.* Aggregation models has-a relationships. The owner object is called an aggregating object, and its class is called an aggregating class. The subject object is called an aggregated object, and its class is called an aggregated class. (Page 374). *An aggregation relationship is usually* *represented as a data field in the aggregating* *class.* (Page 375). //Aggregated Class public class Name { ... } //Aggregated Class public class Address { ... } //Aggregating Class public class Student { private Name name; private Address address; } (Page 375).

Association

*Association is a general binary relationship that* *describes an activity between two classes.* For example, a student taking a course is an association between the Student class and the Course class, and a faculty member teaching a course is an association between the Faculty class and the Course class.

Constructor

*Constructors are used to construct new objects from a class.* *1. Constructors has the same name as the class* *2. Constructors don't have a return type, not even void* *3. *Constructors are designed to perform initializing actions, such as *initializing the data* *fields of objects.* synthax: *ClassName(parameterName : parameterType)* A class normally provides a constructor without arguments (e.g., Circle()). Such a con- structor is referred to as a no-arg or no-argument constructor. *A class may be defined without constructors.* In this case, a public no-arg constructor with an empty body is implicitly defined in the class. This constructor, called a *default constructor,* is *provided automatically only if no constructors* are explicitly defined in the class.

Instance methods vs static methods

*Instance methods* have to be *instantiated* creating an object, where as *static methods* *don't* have to be instantiated. Ex: ???

Passing arrays to methods. Accessing an array from a different method

*When passing an array to a method, the reference of the array is passed to the method. So if you makes changes to the array's elments in another method that array will be changed everywhere.* *public static double averageOfArray(int[ ] arrayName)* *{* *}* //to call the method with the array *averageOfArray(arrayName);*

Constructing a String

*You can create a string object from a string literal* *or from an array of characters.* To create a string object from a *string literal*(a regualr string of characters enclosed inside double quotes): synthax: *String newString = new String(stringLiteral);* Ex: *String message = new String("Welcome to Java");* *Java treats a string literal as a String object.* Thus, the following statement is valid: *String message = "Welcome to Java";*

Array initializer

*array initializer* is a short hand notation that combines creating and initialization in one statement. *variableType[ ] variableName = {value0, value1, value2, value3, value4 };* Ex: *double[ ] myList = {1.1, 1.2, 1.3, 1.4};*

Array to String Conversion

*char[ ] charArray = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'};* *String message = new String(charArray);* *System.out.println("message");* //Prints: *Good Day*

equal

*equals* checks if two arrays are strictly equal. Two arrays are strictly equal if their corresponding elements are the same. They will give a true or false. *int[] list1 = {2, 4, 7, 10};* *int[] list2 = {2, 4, 7, 10};* *int[] list3 = {4, 2, 7, 10};* *System.out.println(java.util.Arrays.equals(list1,* *list2));* // true *System.out.println(java.util.Arrays.equals(list2,* *list3));* // false

Printing two-dimensional Arrays

*for(int row = 0; row < matrix.length; row++)* { *for(int colu = 0; colu < matrix[0].length; colu++)* { *System.out.print(matrix[row][colu] + " ")* } System.out.println( ); }

Date( ) class - Java Library

*java.util.Date;* **Date( )* //Constructs a Date object, for current time **Date(elapseTime: long)* //Contructs a Date object for a given time. **toString( ) : String* //returns a string representation of the date and time **getTime( ): long* //Returns the number of milliseconds **+setTime(elapseTime: long): void* //Sets a new elapse time in the object. Ex: *java.util.Date date = new java.util.Date();* *System.out.println("The elapsed time since Jan 1,* *1970 is " + date.getTime() + " milliseconds");* *System.out.println(date.toString());* displays the output like this: The elapsed time since Jan 1, 1970 is 1324903419651 milliseconds Mon Dec 26 07:43:39 EST 2011

Anonymous object

*new Circle();* or *System.out.println("Area is " + new* *Circle(5).getArea());* The former statement creates a Circle object. The latter creates a Circle object and invokes its getArea method to return its area. An object created in this way is known as an anonymous object.

Methods for Scanner Objects Description

*nextByte()* reads an integer of the byte type. *nextShort()* reads an integer of the short type. *nextInt()* reads an integer of the int type. *nextLong()* reads an integer of the long type. *nextFloat()* reads a number of the float type. *nextDouble()* reads a number of the double type.

Converting from Decimal to Binary

*watch this video:* https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/decimal-to-binary

Programming languages

- Machine language - Assembly Language - High Level Language Machine Language: - The computers native language. - Primitive instructions in the form of binary code. Assembly Languge: - slightly closer to a regular language. - uses short descriptive words - another program called assembler is needed to translate the language into machine language. High Level Language: - English-like - Run on different types of machines - instructions in a high level language are called statements

Random( ) class - Java Library

A Random object can be used to generate random values. When you create a Random object, you have to specify a seed or use the default seed. A seed is a number used to initialize a random number generator. The no-arg constructor cre- ates a Random object using the current elapsed time as its seed. *java.util.Random;* *Random()* //Constructs a Random object with the current time as its seed. *Random(seed: long)* //Constructs a Random object with a specified seed. *nextInt(): int* //Returns a random int value. *nextInt(n: int): int* //Returns a random int value between 0 and n (excluding n). *nextLong(): long* //Returns a random long value. *nextDouble(): double* //Returns a random double value between 0.0 and 1.0 (excluding 1.0). *nextFloat(): float* //Returns a random float value between 0.0F and 1.0F (excluding 1.0F). *nextBoolean(): boolean* //Returns a boolean value *OBS!* If two Random objects have the same seed, they will generate identical sequences of numbers. *NOTE:* The ability to generate the same sequence of random values is useful in software testing and many other applications. In software testing, often you need to reproduce the test cases from a fixed sequence of random numbers.

The String class

A String is immutable its content cannot be changed once the string is created. *- Strings are objects.* *- charAt(index)* obtains character a specefied index *- length( )* returns size of string *- substring* returns substring in a string *- indexOf( )* returns first index of a string *- lastIndexOf( )* retusn last index of a string *- split(delimiter: String): String[ ]* Returns an array of strings consisting of the substrings split by the delimiter. *String[ ] tokens = "Java#HTML#Perl".split("#");* *for (int i = 0; i < tokens.length; i++)* *System.out.print(tokens[i] + " ");* //displays: Java HTML Perl

call stack

A call stack stores the activation records in a last-in, first-out fashion: The activation record for the method that is invoked last is removed first from the stack. For example, suppose method m1 calls method m2, and m2 calls method m3. The runtime system pushes m1's activa- tion record into the stack, then m2's, and then m3's. After m3 is finished, its activation record is removed from the stack. After m2 is finished, its activation record is removed from the stack. After m1 is finished, its activation record is removed from the stack.

Class

A class is a template, blue- print, or contract that defines what an object's data fields and methods will be. *A class is a template for creating objects.* Classes are definitions for objects and objects are created from classes. *You can put the two classes into one file, but* *ONLY ON CLASS IN THE FILE CAN BE PUBLIC.* *OBS!! The public class MUST have the same* *name as the file name.* Therefore, the file name is TestSimpleCircle.java, since TestSimpleCircle is public. Each class in the source code is compiled into a .class file. When you compile TestSimpleCircle.java, two class files TestSimpleCircle.class and SimpleCircle.class are generated *you can test a class by simply adding a main* *method in the same class.*

A *class* as a *datatype*

A class is also a data type. You can use it to declare object reference variables. An object reference variable that appears to hold an object actually contains a reference to that object. Strictly speaking, an object reference variable and an object are different, but most of the time the distinction can be ignored. (Page 359).

Bits and Bytes

A computer is really nothing more than a series of switches. Each switch exists in two states: on or off. Storing information in a computer is simply a matter of setting a sequence of switches on or off. If the switch is on, its value is 1. If the switch is off, its value is 0. These 0s and 1s are interpreted as digits in the binary number system and are called bits (binary digits). The minimum storage unit in a computer is a byte. A byte is composed of eight bits. A small number such as 3 can be stored as a single byte. To store a number that cannot fit into a single byte, the computer uses several bytes. A computer's storage capacity is measured in bytes and multiples of the byte, as follows: ■ A kilobyte (KB) is about 1,000 bytes. ■ A megabyte (MB) is about 1 million bytes. ■ A gigabyte (GB) is about 1 billion bytes. ■ A terabyte (TB) is about 1 trillion bytes. A typical one-page word document might take 20 KB. Therefore, 1 MB can store 50 pages of documents and 1 GB can store 50,000 pages of documents. A typical two-hour high- resolution movie might take 8 GB, so it would require 160 GB to store 20 movies.

Memory

A computer's memory consists of an ordered sequence of bytes for storing programs as well as data that the program is working with. You can think of memory as the computer's work area for executing a program. A program and its data must be moved into the computer's memory before they can be executed by the CPU. Every byte in the memory has a unique address, as shown in Figure 1.2. The address is used to locate the byte for storing and retrieving the data. Since the bytes in the memory can be accessed in any order, the memory is also referred to as random-access memory (RAM). (RAM) is a volatile (easily changed) form of data storage: any information that has been stored in memory (i.e., saved) is lost when the system's power is turned off.

Driver class

A driver class is where you test parts of code to be used in a larger program. Its much easier dividing and subdividing code when working on and debugging programs.

foreach loop

A foreach loop enables you to traverse the array sequentially without using an index variable. Synthax: *for (variableType : arrayName) { }* Ex: *for (int i: myList) { * *System.out.prinln(i);* *}* You can read the code as "for each element *i* in *myList*, do the following." Note that the variable, i, must be declared as the same variable-type as the elements in myList. (which is int in the example).

source code or source program

A program written in a high level language

regular expression (regex)

A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. You can match, replace, or split a string by specifying a pattern. This is an extremely useful and powerful feature. (Page 388). Often used when you will need to write code that validates user input, such as to check whether the input is a number, a string with all lowercase letters, or a Social Security number.

Stack

A stack is a data structure that holds data in a last-in, first-out fashion. Stacks have many applications. For example, the compiler uses a stack to process method invocations. When a method is invoked, its parameters and local variables are pushed into a stack. When a method calls another method, the new method's parameters and local variables are pushed into the stack. When a method finishes its work and returns to its caller, its associated space is released from the stack. (Page 378).

BUS

A system that interconnects all the computer's components. The bus is built into the computer's motherboard, which is a circuit case that connects all of the parts of a computer together. - CPU (centra processing unit). - Memory - Storage devices (disks and CDs) - Input devices (mouse and keyboard) - Output devices (monitors and printers) - Communication devices (modems and network interface cards)

length of Two Dimenasional Array

A two-dimensional array is actually an array in which each element is a one-dimensional array. The length of an array x is the number of elements in the array, which can be obtained using x.length. x[0], x[1], . . . , and x[x.length-1] are arrays. Their lengths can be obtained using x[0].length, x[1].length, . . . , and x[x.length-1].length.

Variables of Primitive Types VS Refrence Types

A variable of a primitive type holds a value of the primitive type, and a variable of a reference type holds a reference to where an object is stored in memory. A variable of a primitive type holds a value of the primitive type, and a variable of a reference type holds a reference to where an object is stored in memory. When you assign one variable to another, the other variable is set to the same value. For a variable of a primitive type, the real value of one variable is assigned to the other variable. For a variable of a reference type, the reference of one variable is assigned to the other vari- able.AsshowninFigure9.8,theassignmentstatementi = jcopiesthecontentsofjintoi

array index out of bounds exception - error

Accessing an array out of bounds is a common programming error that throws a runtime *ArrayIndexOutOfBoundsException*. To avoid it, make sure that you *do not use an index beyond arrayName.length - 1.* Programmers often mistakenly reference the first element in an array with index 1, but it should be 0.

Array of Objects

An array can hold objects as well as primitive type values. For example, the following statement declares and creates an array of ten Circle objects: *Circle[ ] circleArray = new Circle[10];* To initialize circleArray, you can use a for loop like this one: *for (int i = 0; i < circleArray.length; i++) {* *circleArray[i] = new Circle( );* *}*

unicode

An encoding scheme established by the Unicode Consortium to support the interchange, processing and display of written texts in the world\s diverse languages. The Unicode standard therefore has been extended to allow up to 1,112,064 characters. Those characters that go beyond the original 16-bit limit are called supplementary characters. Java supports the supplementary characters. The processing and representing of supplementary characters are beyond the scope of this book. For simplicity, this book considers only the original 16-bit Unicode characters. These characters can be stored in a char type variable.

interpreter

An interpreter reads a statement of code and translates it into machine code and then executes it right away

composition

An object can be owned by several other aggregating objects. If an object is exclusively owned by an aggregating object, the relationship between the object and its aggregating object is referred to as a composition. (Page 374).

Object

An object is an instance of a class. Objects of the same type are defined using a common class. You can create many objects/instances from a class. "You can make as many apple pies as you want from a single recipe." The *new* operator is used to create an object from the constructor. *className objectName = new className( );* Ex: //Creates object with radius 25. *SimpleCircle circle1 = new SimpleCircle(25);* //Constructor with parameter *SimpleCircle(double newRadius)* *{radius = newRadius}* Newly created objects are allocated in the memory. They can be accessed via reference variables. Strictly speaking, an object reference variable and an object are different, but most of the time the distinction can be ignored. Therefore, it is fine, for simplicity, to say that myCircle is a Circle object rather than use the longer-winded description that myCircle is a variable that contains a reference to a Circle object.

Point2D class - Java Library

Book: INtroduction to Java Programming, Comprehensive Edition 10th. Chapter: 9 Page: 336

Stepwise Refinement

Breaks a large problem into smaller managable subproblems. Each subproblem can be implemented using a method. This approach makes the program easier to write, reuse, deubbug, test, modify and maintain.

printing char arrays

Char arrays can be printed in one statement. *char[ ] city = {'S', 't', 'o', 'c', 'k', 'h', 'o', 'l', 'm'};* *System.out.print(city);*

Class Abstraction

Class abstraction is the separation of class implementation from the use of a class. (Page 366).

Reading input from the console

Console input is not directly supported in Java, but you can use the Scanner class to create an object to read input from System.in Scanner userInput = new Scanner(System.in); string name = userInput; OBS! You must import the scanner class in the beginng of your program. import java.util.Scanner; System.out.println("Enter your rollno"); int rollno=sc.nextInt(); System.out.println("Enter your name"); String name=sc.next(); System.out.println("Enter your fee"); double fee=sc.nextDouble(); *****OBS! By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. You can write multiple integers/floats with space inbetween and the Scanner will read them seperatly******

valueOf( )

Converting a number into a string - used the overloaded static valueOf method. This can also be used to converty a char or an array of chars into a string. Ex: Convert a double value 5.44 to a string. double myValue = 5.44; *String.valueOf(myValue);*

Boxing and Unboxing

Converting a primitive value to a wrapper object is called boxing. The reverse conversion is called unboxing. The compiler will automatically box a primitive value that appears in a context requiring an object, and will unbox an object that appears in a context requiring a primitive value. This is called autoboxing and autounboxing. Ex: *Integer intObject = new Integer(2); * is equivalent to *Integer intObject = 2;*

Activation Record

Each time a method is invoked, the system creates an activation record (also called an acti- vation frame) that stores parameters and variables for the method and places the activation record in an area of memory known as a call stack. A call stack is also known as an execution stack, runtime stack, or machine stack, and it is often shortened to just "the stack." When a method calls another method, the caller's activation record is kept intact, and a new activation record is created for the new method called. When a method finishes its work and returns to its caller, its activation record is removed from the call stack.

Encapsulation

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. To achieve encapsulation in Java: *[]*Declare the variables of a class as private. *[]*Provide public setter and getter methods to modify and view the variables values. https://www.tutorialspoint.com/java/java_encapsulation.htm

ragged array

If you don't know the values in a ragged array in advance, but do know the sizes—say, the same as before—you can create a ragged array using the following syntax: *int[][] triangleArray = new int[5][]; * triangleArray[0] = new int[5]; triangleArray[1] = new int[4]; triangleArray[2] = new int[3]; triangleArray[3] = new int[2]; triangleArray[4] = new int[1];

Immutable

Immutable objects are simply objects whose state (the object's data) cannot change after construction. http://www.javapractices.com/topic/TopicAction.do?Id=29

Copy Arrays

In Java, you can use *assignment statements ( = )* to copy primitive data type variables, *but not arrays.* Assigning one array variable to another array variable actually *copies one reference to another and makes both variables point to the same memory location.* There are 3 ways to copy an array: *1.* Use a loop to copy individual elements one by one. *2.* Use the static *arraycopy* method in the *Systems* class. *3.* Use the *clone* method to copy arrays.(introduced in ch13) *1. Loop:* int[ ] originialArray = {1, 2, 3, 4, 10}; int [ ] newArray = new int[originalArray.length]; for(int i = 0; i < originalArray.length; i++) { newArray[i] = originalArray[i]; } *2. arraycopy method:* System.arraycopy(originalArray, orgPos, newArray, newPos length); //orgPos and newPos indicate starting poisitions. Number of elements copied is is indicated by length. or System.arraycopy(originalArray, 0, newArray, 0 length);

Inheritance

Inheritance is a powerful and important feature for reusing software. Inheritance allows you to define a general class (a *superclass*) and later extend it to more specialized classes(*subclasses*). The subclasses inherit the properties and methods of the superclass.

JDK

Java Devlopmentaltool Kit. The JDK consists of a set of separate programs, each invoked from a command line, for developing and testing Java programs. Instead of using the JDK, you can use a Java devel- opment tool (e.g., NetBeans, Eclipse, and TextPad)—software that provides an integrated development environment (IDE) for developing Java programs quickly.

Java SE - Stadard Edition Java EE - Enterprise Edition Java ME - Micro Edition

Java SE is the foundation upon which all other Java technology is based. There are many versions of Java SE. Java is a full-fledged and powerful language that can be used in many ways. It comes in three editions: ■ Java Standard Edition (Java SE) to develop client-side applications. The applica- tions can run standalone or as applets running from a Web browser. ■ Java Enterprise Edition (Java EE) to develop server-side applications, such as Java servlets, JavaServer Pages (JSP), and JavaServer Faces (JSF). ■ Java Micro Edition (Java ME) to develop applications for mobile devices, such as cell phones.

Java Applets

Java initially became attractive because Java programs can be run from a Web browser. Such programs are called applets. Applets employ a modern graphical interface with but- tons, text fields, text areas, radio buttons, and so on, to interact with users on the Web and process their requests. Applets make the Web responsive, interactive, and fun to use. Applets are embedded in an HTML file. HTML (Hypertext Markup Language) is a simple scripting language for laying out documents, linking documents on the Internet, and bringing images, sound, and video alive on the Web.

Encoding

Mapping a (char) character to its binary representation

Methods

Methods can be used to define reusable code and organize and simplfy coding. A method definition consists of its method name, parameters, return value type, and body. synthax: modifier returnValueType methodName(list of parameters) { // Method body; } A method is a collection of statements grouped together to perform an operation. Ex: System.out.println(); *public static int sum(int i1, int i2)* { int result = 0; for(int i = i1; i <= i2; i++) result += 1; return result; } System.out.println("Sum from 1 to 10 is " + *sum(1, 10)*); Understanding call stacks helps you to comprehend how methods are invoked.

overloaded constructor

Multiple constructors with the same name, but different parameters.

Multiprocessing

Multiprocessing, or parallel processing, uses two or more processors together to per- form subtasks concurrently and then combine solutions of the subtasks to obtain a solution for the entire task. It is like a surgical operation where several doctors work together on one patient.

Multiprogramming

Multiprogramming allows multiple programs to run simultaneously by sharing the same CPU. The CPU is much faster than the computer's other components. As a result, it is idle most of the time—for example, while waiting for data to be transferred from a disk or waiting for other system resources to respond. A multiprogramming OS takes advantage of this situation by allowing multiple programs to use the CPU when it would otherwise be idle. For example, multiprogramming enables you to use a word processor to edit a file at the same time as your Web browser is downloading a file.

Multithreading

Multithreading allows a single program to execute multiple tasks at the same time. For instance, a word-processing program allows users to simultaneously edit text and save it to a disk. In this example, editing and saving are two tasks within the same application. These two tasks may run concurrently.

processing input two-Dimensional Arrays

Nested for loops are often used to process a two-dimensional array. Ex: int[ ][ ] matrix = new int[10][10]; java.util.Scanner input = new Scanner(System.in); System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns"); *for(int row = 0; row < matrix.length; row++)* { *for(int colu = 0; colu < matrix[0].length; colu++)* { *matrix[row][colum] = input.nextInt( );* } }

immutable

Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create *an object* *whose contents cannot be changed once the* *object has been created.* We call such an object as immutable object and its class as immutable class. The String class, for example, is immutable. (Page 353). You can define immutable classes to create immutable objects. The contents of immutable objects cannot be changed. (Page 353). If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable. For example, the following Student class has all private data fields and no setter methods, but it is not an immutable class. (Page 354).

NullPointerException

NullPointerException is a common runtime error. It *occurs when you invoke a method on a reference* *variable with a null value.* Make sure you assign an object reference to the variable before invoking the method through the reference variable

Refreence Variables and Refrence Types

Objects are accessed via the object's reference variables, which contain references to the objects. Such variables are declared using the following syntax: ClassName objectRefVar; A class is essentially a programmer-defined type. A class is a reference type, which means that a variable of the class type can reference an instance of the class. The following statement declares the variable myCircle to be of the Circle type: Circle myCircle; The variable myCircle can reference a Circle object. The next statement creates an object and assigns its reference to myCircle: myCircle = new Circle(); You can write a single statement that combines the declaration of an object reference variable, the creation of an object, and the assigning of an object reference to the variable with the fol- lowing syntax: ClassName objectRefVar = new ClassName(); Here is an example: Circle myCircle = new Circle(); The variable myCircle holds a reference to a Circle object

Controlling and Monitoring System Activities

Operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the monitor, keeping track of files and folders on storage devices, and controlling peripheral devices, such as disk drives and printers. An operating system must also ensure that different programs and users working at the same time do not interfere with each other. In addition, the OS is responsible for security, ensuring that unauthorized users and programs are not allowed to access the system.

overloading methods

Overloading methods enables you to define the methods with the same name as long as their signatures are different. The max method that was used earlier works only with the int data type. But what if you need to determine which of two floating-point numbers has the maximum value? The solu- tion is to create another method with the same name but different parameters, as shown in the following code: public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } If you call *max* with *int* parameters, *the max method that expects int parameters will be invoked.* if you call *max* with *double* parameters, *the max method that expects double parameters will be invoked.* This is referred to as method overloading; that is, two methods have the same name but different parameter lists within one class. The Java compiler deter- mines which method to use based on the method signature. Overloading methods can make programs clearer and more readable. Methods that per- form the same function with different types of parameters should be given the same name.

package

Packages can be used to organize classes. To do so, you need to add the following line as the first noncomment and nonblank statement in the program: *package packageName;*

Storage devices

Programs and data are permanently stored on storage devices and are moved, when the computer FIGURE 1.2 locations. Memory stores data and program instructions in uniquely addressed memory actually uses them, to memory, which operates at much faster speeds than permanent storage devices can. There are three main types of storage devices: ■ Magnetic disk drives ■ Optical disc drives (CD and DVD) ■ USB flash drives

runtime errors

Runtime errors are errors that cause a program to terminate abnormally. They occur while a program is running if the environment detects an operation that is impossible to carry out. Input mistakes typically cause runtime errors.

matches(regex)

Similar to equals method but more powerful. *Java.** in the preceding statements is a regular expression. It describes a string pattern that begins with Java followed by any zero or more characters. Ex: *"Java is fun".matches(Java.*)* *"Java is powerful".matches(Java.*)* //All statements evaluates true. *"440-02-4534".matches("\\d{3}-\\d{2}-\\d{4}")* \\d represents a single digit, and \\d{3} represents three digits.

Arrays

Stores a collection of data. synthax: *variableType[ ] arrayName;* or *variableType arrayName[ ];* Ex: *String[] names;* or *double[] myList;* Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the refer- ence to an array. You cannot assign elements to an array unless it has already been created. After an array variable is declared, you can create an array by using the new operator and assign its reference to the variable with the following syntax: *arrayName = new variableType[arraySize]* Ex: *myList = new double[10];* You can also combine everything in one statement: synthax: *variableType[ ] arrayName = new variableType[arraysSize];* Ex: *String[ ] employeeName = new String[10];* *double[ ] myList = new double[20];* Technically, an array variable only holds a refrence to an array. MyList is actually a variable that contains a reference to an array of 20 double elements. OBS! When space for an array is allocated, the array size must be given, specifying the number of ele- ments that can be stored in it. The size of an array cannot be changed after the array is created.

substring

String message = "Welcome to Java"; String message = message.substring(0, 11) + "HTML"; // The string message now becomes Welcome to HTML.

Formatting String (similar to printf)

String myString = "0.123"; myString = *String.format("%.2f, ");* System.out.println(myString); //prints 0.12

Convert String to Double/Integer

String myString = "123"; *double value = Double.parseDouble(myString);* System.out.println(value); //prints 123.0 int value = Integer.parseInt(myString); System.out.println(value); //prints 123

Writing output onto the console

System.out.println("Hello..."); System.out.println("2 + 2 = " + 2 + 2); System.out.println(x = 1); is equivalent to x = 1; System.out.println(x);

dot operator AKA *object member access operator*

The *dot ( . ) operator* access the data fields. *objectName.dataField* references a data field in the object. *objectName.method(arguments)* invokes a method on the object. //acessing radius value and changing it to 20. *circle1.radius = 20* //Gives access to the getArea method from the SimpleCircle class. *SimpleCircle circle1 = new SimpleCircle(25);* *circle1.getArea( )* Caution Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle.getArea()? The answer is no. *All the* *methods in the Math class are static methods,* *which are defined using the static keyword.* However, getArea() is an instance method, and thus nonstatic. It must be invoked from an object using objectRefVar.methodName(arguments)

*The Array Class* selection sort binary search

The *java.util.Arrays* class contains various static methods for sorting and searching arrays, comparing arrays, filling array elements, and returning a string representation of the array. These methods are overloaded for all primitive types. You can use the *sort* or *parallelSort* method to sort a whole array or a partial array. For example, the following code sorts an array of numbers and an array of characters. *double[ ] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};* *java.util.Arrays.sort(numbers);* // Sorts the whole array. *java.util.Arrays.parallelSort(numbers);* // Sorts the whole array. *char[ ] chars = {'a', 'A', '4', 'F', 'D', 'P'};* *java.util.Arrays.sort(chars, 1, 3);* // Sorts part of the array *java.util.Arrays.parallelSort(chars, 1, 3); * // Sorts part of the array. Invoking *sort(numbers)* sorts the whole array numbers. Invoking *sort(chars, 1, 3)* sorts a partial array from chars[1] to chars[3-1]. *parallelSort is more efficient if your computer *has multiple processors.* You can use the binarySearch method to search for a key in an array. The array must be pre- sorted in increasing order. If the key is not in the array, the method returns -(insertionIndex + 1). *int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70,* *79}; System.out.println("1. Index is " +* *java.util.Arrays.binarySearch(list, 11));* *System.out.println("2. Index is " +* *java.util.Arrays.binarySearch(list, 12));* *char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};* *System.out.println("3. Index is " +* *java.util.Arrays.binarySearch(chars, 'a'));* *System.out.println("4. Index is " +* *java.util.Arrays.binarySearch(chars, 't'));*

Base 10 number system

The Base10 number system is the common decimal system we use every day. *1 2 3 4 5 6 7 8 9* *watch this video:* https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/number-systems-introduction

compiler

The Compiler translates the whole source code into machine code and then creates a file which then can be executed. (a) An interpreter translates and executes a program one statement at a time. (b) A compiler translates the entire source program into a machine-language file for execution.

Classes from the Java Library

The Java API contains a rich set of classes for developing Java programs.

Java bytecode

The Java bytecode is similar to machine instructions but is architecture neutral and can run on any platform that has a Java Virtual Machine (JVM). Rather than a physical machine, the virtual machine is a program that interprets Java bytecode. This is one of Java's primary advantages: Java bytecode can run on a variety of hardware plat- forms and operating systems. Java source code is compiled into Java bytecode and Java byte- code is interpreted by the JVM. Your Java code may use the code in the Java library. The JVM executes your code along with the code in the library.

Java Language Specification

The Java language specification is a technical definition of the Java programming language's syntax and semantics. You can find the complete Java language specification at http://docs.oracle.com/javase/specs/.

Exponential Operands

The Math.pow method can be used to compute a^b. System.out.println(Math.pow(2, 3)); //prints 8 //2^3 = 8;

Scheduling Operations

The OS is responsible for scheduling programs' activities to make efficient use of system resources. Many of today's operating systems support techniques such as multiprogramming, multithreading, and multiprocessing to increase system performance.

The StringBuilder and StringBuffer

The StringBuilder and StringBuffer are similar to the String class except that the String class is immutable. In general, the StringBuilder and StringBuffer classes can be used wherever a string is used. StringBuilder and StringBuffer are more flexible than String. You can add, insert, or append new contents into StringBuilder and StringBuffer objects, whereas the value of a String object is fixed once the string is created. The StringBuilder class is similar to StringBuffer except that the methods for modifying the buffer in StringBuffer are synchronized, which means that only one task is allowed to execute the methods. Use StringBuffer if the class might be accessed by multiple tasks concurrently, because synchronization is needed in this case to prevent corruptions to StringBuffer. (OBS! StringBuffer will be covered much later, in chapter 30) (Page 392-393).

StringBuilder

The StringBuilder class has three constructors and more than 30 methods for managing the builder and modifying strings in the builder. You can create an empty string builder or a string builder from a string using the constructors, (Page 393). Three Constructors: *- StringBuilder( );* *- StringBuilder(capacity: int);* *- StringBuilder(s: String)* capacity. Internally, a string builder is an array of characters, so the builder's capacity is the size of the array. If the builder's capacity is exceeded, the array is replaced by a new array. The new array size is 2 * (the previous array size + 1).

^ Operator exclusive-or Operator

The ^ operator is called the exclusive-or operator. think of it as "this or that, but not both." Ex:

API Library

The application program interface (API), also known as library, contains predefined classes and interfaces for developing Java programs. You can view and download the latest version of the Java API at http://download.java.net/jdk8/docs/api/.

*Base 2* number system *The Binary number system*

The binary system: *1s and 0s* *watch this video:* https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/number-systems-introduction

break; vs continue;

The break statement breaks out of the loop, and the continue statement breaks out of the current iteration in the loop. An iteration is referrd as one-time execution of the the body of a loop.

capacity method

The capacity() method returns the current capacity of the string builder. The capacity is *the number* *of characters the string builder is able to store* *without having to increase its size.* (Page 395).

Central Processing Unit - CPU

The central processing unit is the computer's brain. It retrieves instructions from CPU memory and executes them. The CPU has 2 components: - Control Unit - Arthimetic/Logic unit Control Unit: coordinates the actions of the other components. Arthimetic/Logic unit: performs numeric operations(addition, subtraction, multiplication, division) and the logical operations(comparisons) Today's CPUs are built on small silicon semiconductor chips that contain millions of tiny electric switches, called transistors, for processing information. Every computer has an internal clock, which emits electronic pulses at a constant rate. These pulses are used to control and synchronize the pace of operations. CPUs were originally developed with only one core. The core is the part of the processor that performs the reading and executing of instructions. A multicore CPU is a single component with two or more independent cores. Today's consumer comput- ers typically have two, three, and even four separate cores. Soon, CPUs with dozens or even hundreds of cores will be affordable. https://www.youtube.com/watch?v=cNN_tTXABUA

charAt method

The charAt(index) method returns the character at a specific index in the string builder. The index is 0 based. The first character of a string builder is at index 0, the next at index 1, and so on. The index argument must be greater than or equal to 0, and less than the length of the string builder. (Page 395). Ex: for(int i = 0; i < s.length(); i++) { if(Character.isLetterOrDigit(s.charAt(i))) stringBuilder.append(s.charAt(i)); } //Filters all invalid character except letters and digits.

Class Relationships

The common relationships among classes are *association, aggregation, composition,* and *inheritence.*

Machine language

The computers instructions. native language = binary code.

extends

The extends keyword tells the compiler that the subclass extends the super class, thus inheriting the superclass methods.

*this* keyword

The keyword *this* refers to the object itself. It can also be used inside a constructor to invoke another constructor of the same class. *this* can access hidden static variables/instance variables. Same as ClassName.staticVariableName. *this* can be used to invoke another constructor of the same class. Suppose that f1 and f2 are two objects of F. Invoking f1.setI(10) is to execute *this.i = 10*, where this refers f1 Invoking f2.setI(45) is to execute *this.i = 45*, where this refers f2 The this keyword gives us a way to reference the object that invokes an instance method. Toinvokef1.setI(10), this.i = i is executed, which assigns the value of parameter i to the data field i of this calling object f1.

The *main* method

The main method is just a regular method that you can pass arguments from the command line. main has the parameter *String[ ] args*. Ex: *public class A* *{* *public static void main(String[] args)* *{* *String[] strings = {"New York", "Boston",* *"Atlanta"};* *TestMain.main(strings);* *}* *}* //You can pass strings to a main method from the command line when you run the program. //Enter in command line: *java TestMain arg0 arg1 arg2* //more on Ch7 pg272

*Base 16* number system *Hexadecimal System*

The numbers 0 through 9 are the same in both systems; however, the decimal numbers 10 through 15 are represented by the letters A through F. A = 10 B = 11 C = 12 D = 13 E = 14 F = 15 The hexadecimal system is commonly used by programmers to describe locations in memory because it can represent every byte (i.e., eight bits) as two consecutive hexadecimal digits instead of the eight digits that would be required by binary (i.e., base 2) numbers and the three digits that would be required with decimal numbers. In addition, it is much easier for humans to read hexadecimal numbers than binary numbers, and it is not much more difficult for computer professionals to read hexadecimal numbers than decimal numbers. *watch this video:* https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/hexadecimal-number-system

Operating System (OS)

The operating system (OS) is the most important program that runs on a computer. The OS manages and controls a computer's activities. The major tasks of an operating system are as follows: ■ Controlling and monitoring system activities ■ Allocating and assigning system resources ■ Scheduling operations

Allocating and Assigning System Resources

The operating system is responsible for determining what computer resources a program needs (such as CPU time, memory space, disks, input and output devices) and for allocating and assigning them to run the program.

private modifier

The private modifier makes methods and data fields accessible only from within its own class. *To prevent direct modifications of data fields,* *you should declare the data fields private, using* *the private modifier.* This is known as data field encapsulation. Making data fields private protects data and makes the class easy to maintain. The private modifier restricts access to its defining class, the default modifier restricts access to a package, and the public modifier enables unrestricted access. The private modifier applies only to the members of a class. The public modifier can apply to a class or members of a class. Using the modifiers public and private on local variables would cause a compile error. In most cases, the constructor should be public. However, if you want to prohibit the user from creating an instance of a class, use a private constructor.

split(regex)

The replaceAll, replaceFirst, and split methods can be used with a regular expression. *String[] tokens = "Java,C?C#,C++".split("[.,:;?]");* *for (int i = 0; i < tokens.length; i++)* *System.out.println(tokens[i]);* In this example, the regular expression *[ . , : ; ? ]* specifies a pattern that matches *. , ,, : , ; or ?* Each of these characters is a delimiter for splitting the string. Thus, the string is split into *Java, C, C#, and C++,* which are stored in array tokens.

replaceAll(regex)

The replaceAll, replaceFirst, and split methods can be used with a regular expression. The following statement returns a new string that replaces $, +, or # in a+b$#c with the string NNN. *String s = "a+b$#c".replaceAll("[$+#]", "NNN");* *System.out.println(s);* Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is aNNNbNNNNNNc.

setLength method

The setLength(newLength) method sets the length of the string builder. If the newLength argument is less than the current length of the string builder, the string builder is truncated to contain exactly the number of characters given by the newLength argument. If the newLength argument is greater than or equal to the current length, sufficient null characters (\u0000) are appended to the string builder so that length becomes the newLength argument. The newLength argument must be greater than or equal to 0. (Page 395).

calling a Method

There are two ways of calling a method. 1.Call a method - returns a value. 2.Invoke a method. //Calling the 'sum' method System.out.println("Sum from 1 to 10 is " + *sum(1, 10)*);

Variable-Length Argument List

This is useful when you don't know how many variables you will pass into a method. When invoking a method with a vari- able number of arguments, Java creates an array and passes the arguments to it. In the method declaration, you specify the type followed by an *ellipsis (...)*. *Only one variable-length parameter may be* *specified in a method, and this parameter must* *be the last parameter. Any regular parameters* *must precede it.* Instead of: *public static int numbers(int num1, int num2, int* *num3...)* *{//statements}* use *public static int numbers(int...num)* *{//statements}* Very helpful video: https://www.youtube.com/watch?v=BFL1oWnEO2k

arrays assigning values

To assign value to an element/index of an array: synthax: *arrayName[index] = value;* Ex: *myList[0] = 15;* //puts the value 15 in the first index of the myList array.

Convert string to int

To convert a string into an int value, use the Integer.parseInt method. synthax: int intValue = Integer.parseInt(intString); double doubleValue = Double.parseDouble(doubleString);

The getter and setter method

To make a private data field accessible, provide a getter method to return its value. To enable a *private data field to be updated, provide a setter* method to set a new value. A getter method is also referred to as an *accessor* and a setter to a *mutator*. getter: *public returnType getPropertyName( )* setter: *public void setPropertyName(dataType propertyValue)* Ex: *private int x = 0;* *public int getX* *{* *return x;* *}* *public int setX* *{* *this.x = x;* *}* //In another class you can now access the private fields. *ClassName object1 = new ClassName( );* //sets private int x to 25. *object1.setX(25)* //prints the private field. *System.out.println("X is " + object1.getX( ))*

RIA Rich Internet Application

Today, you can use Java to develop rich Internet appli- cations. A rich Internet application (RIA) is a Web application designed to deliver the same features and functions normally associated with deskop applications.

String to Array Conversion

Use the 'toCharArray' method to convert a string into an array. Ex: *char[ ] chars = "Java".toCharArray( );* Thus, chars[0] is J, chars[1] is a, chars[2] is v, and chars[3] is a.

Returning an array from a method

When a method returns an array, the reference of the array is returned. Ex: *public static int[ ] reverse(int[ ] list)* { *int[ ] result = new int[list.length];* *for(int i = 0, j = result.length -1; i < list.length; i++, j--)* { *result[j] = list[i];* } *return result;* }

toString (with Arrays Class)

You can also use the toString method to return a string that represents all elements in the array. This is a quick and simple way to display all elements in the array. *int[ ] list = {2, 4, 7, 10};* *System.out.println(Arrays.toString(list));* //Displays: 2 4 7 10;

Modifying Strings in the String Builder

You can append new contents at the end of a string builder, insert new contents at a specified position in a string builder, and delete or replace characters in a string builder, using its methods (Page 393) StringBuilder myStringBuilder = new StringBuilder(); *//Append(to add) - append(adds) strings and* *characters into stringBuilder to form a new string.* myStringBuilder.append("Welcome"); myStringBuilder.append(' '); myStringBuilder.append("to"); myStringBuilder.append(' '); myStringBuilder.append("Java"); System.out.println("Append: " + myStringBuilder); *//Insert - inserts a string to another string* myStringBuilder.insert(11, "HTML and "); System.out.println("insert: " + myStringBuilder); *//Deletes charIndex between 8 and 19* myStringBuilder.delete(8, 19); System.out.println("Delete: " + myStringBuilder); *//Deletes a single char at index 9* myStringBuilder.deleteCharAt(9); System.out.println("DeleteCharAt 11: " + myStringBuilder); *//Replaces the string between indexes 0 and 12* *with the string "welcome to Java"* myStringBuilder.replace(0, 12, "welcome to Java"); System.out.println("Replace: " + myStringBuilder); *//Sets/changes the char 'w' at index 0 to char 'W'* myStringBuilder.setCharAt(0, 'W'); System.out.println("setCharAt 0 to W: " + myStringBuilder); *//Reverses a string* myStringBuilder.reverse(); System.out.println("Welcome to Java in reverse is: " + myStringBuilder);

Passing objects to methods

You can pass objects to methods. Like passing an array, passing an object is actually passing the reference of the object. public static void(nameOfObject xyz) { xzy.getArear( ); } More on pg347

length/size of an array

You can use *.length* to get the size of an array. *arrayName.length* //gives you a value/size of the array. The default value/size of the array when created is 0. *Array indices are 0 based; that is, they range from 0 to arrayName.length-1.*

fill

You can use the fill method to fill in all or part of the array. For example, the following code fills list1 with 5 and fills 8 into elements list2[1] through list2[5-1]. int[] list1 = {2, 4, 7, 10}; int[] list2 = {2, 4, 7, 7, 7, 10}; java.util.Arrays.fill(list1, 5); // Fill 5 to the whole array java.util.Arrays.fill(list2, 1, 5, 8); // Fill 8 to a partial array

divide-and-conquer strategy

also known as *stepwise refinement*. Used when writing a large program to decompose it to subproblems. The subproblems can be further decomposed into smaller, more managable problems. *Top-down Design* - draw a top-down structure chart showing each problem and subproblems and the subproblems subproblem. Until you have a tree of problems to solve. *Stubs* - a temporary substitute for yet-to-be-developed code. Simulate the behavior of a code you want implemented. Stubs enables you to quickly build the framework of the program.

binary search

ch7 pg269

constructors vs methods

constructors creat objects and methods manipulate objects

nested forloops

for (int j = 1; j <= 3; j++) { for (int k = 1; k<= 4; k++) { System.out.println('*'); } } //How many asteriks will the loop output? //Answer: The first loop will loop the nested loop 3times. The nested loop will loop 4times. //3 times 4 is 12. 12 asteriks will be outputed.

Formatting Numeric Print Out printf format

format and printf, are equivalent to one another. System.out.printf("float variable is *%f*", floatVar); System.out.printf("integer variable is *%d*", intVar); System.out.printf("string is *%s*", stringVar); The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out. Thus, you can use format or printf anywhere in your code where you have previously been using print or println. %c character %d decimal (integer) number (base 10) %e exponential floating-point number %f floating-point number %i integer (base 10) %o octal number (base 8) %s a string of characters %u unsigned decimal (integer) number %x number in hexadecimal (base 16) %% print a percent sign \% print a percent sign

Transistors

https://www.youtube.com/watch?v=OwS9aTE2Go4

Summing all indexes in two-Dimensional Array (by column)

int total = 0; for(int colu = 0; colu < matrix[0].length; colu++) { for(int row = 0; row < matrix.length; row++) { total = total + matrix[row][colu]; } }

Summing all indexes in two-Dimensional Array (by row)

int total = 0; for(int row = 0; row < matrix.length; row++) { for(int colu = 0; colu < matrix[0].length; colu++) { total = total + matrix[row][colu]; } }

toString method

returns a String representation of an object. Ex: stringBuilder.toString( ); //Converts stringBuilder to a Sring.

method abstraction

seperating the use of a method from its implementation. The client can use a method without knowing how it is implemented, The details of the implementation are encapsuled in the method and hidden from the client who invokes the method. This is also known as *information hiding or encapsulation*. If you change the implementation, the client program will not be affected, provided that you do not change the method signature. You have already used the System.out.print method to display a string and the max method to find the maximum number. *You know how to write the code to invoke these methods in your program, but as a user of these methods, you are not required to know how they are implemented*.

Two Dimensional Arrays

synthax: *variableType[ ] [ ] arrayName;* variableType[*row*] [*colum*] arrayName; Ex: declare a two-dimensional array *int[ ] [ ] matrix;* Ex: create a two-dimensional array *matrix = new int[5] [3];* 000 000 000 000 To assign value to a specific index: Assign 7 to *row 2 colum 1*. *matrix[2] [1] = 7;* [0] [1] [2] [0] 0 0 0 [1] 0 0 0 [2] 0 *7* 0 [3] 0 0 0 *Array initializer to declare, create and initialize a* *two dimensional array:* *int[ ] [ ] array =* *{* *{1, 2, 3},* *{4, 5, 6},* *{7, 8, 9}* *};*

constant variables

synthax: final double pi = 3.1415

Copy a substring into another String

synthax: getChars(int srcBegin, int srcEnd, char[ ] dst, int dstBegin); For example, the following code copies a substring "3720" in "CS3720" from index 2 to index 6-1 into the character array "dst" starting from index 4. *char[] dst = {'J', 'A', 'V', 'A', '1', '3', '0', '1'};* *"CS3720".getChars(2, 6, dst, 4);* //char[ ] dst is now JAVA3720 (Page 389).

Generate random numbers

use the *Random method* from the *Math class*. Ex: import java.util.Random; Random ranNum = new Random(); int randomNumber = ranNum.nextInt(9) + 1; //Generates a number from 1 - 10.

pass by value

when you invoke a method with an argument, the value of the argument is passed to the parameter. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method.


संबंधित स्टडी सेट्स

Exam 2 History and Systems Psychology

View Set

NT511 - Gospels and Acts Final Exam

View Set

Chapter 2 Communication and Teamwork

View Set

Ch. 15 - Succession Planning and Strategies for Harvesting and Ending

View Set

AP Euro: Chapter 20 The Industrial Revolution

View Set