Download presentation
Presentation is loading. Please wait.
1
MID-TERM TEST REVIEW FOR CECS 220
PRESENTED BY REACH
2
Java Language: BASIC RULES
Java is case sensitive Identifier names should be descriptive and readable Keywords are reserved words that cannot be used as identifier names Java generally ignores whitespace (except when it is used to separate words) Proper formatting of your codes is important for readability Variable is named memory location used to hold a value of a particular type Accessing a variable leaves it intact but an assignment statement overwrites it Constants hold a particular value for the duration of their existence
3
Example 1: VARIABLES Is the following a valid name for a variable in Java? _special_character A.) Yes B.) No $vari_A1 A, A
4
SCANNER CLASS This class is part of the standard Java class library
Provides a convenient way for reading input values of various types { String message; Scanner scan = new Scanner(System.in); System.out.println(“Enter a line of text: “); message = scan.nextLine(); System.out.println(“Your text: “ + message); }
5
Scanner Class Scanner scan = new Scanner(System.in);
For integer: scan.nextInt() For double: scan.nextDouble() For string: scan.nextLine() For byte: scan.nextByte() For float: scan.nextFloat() For Boolean: scan.nextBoolean()
6
JAVA CLASSES AND OBJECTS: RANDOM CLASS
import java.util.Random; { Random random = new Random(); int num1, num3; float num2, num4; num1 = random.nextInt(); System.out.println(num1); num2 = random.nextFloat(); System.out.println(num2); num3 = random.nextInt(10); System.out.println(num3); num4 = random.nextFloat() * 5; System.out.println(num4); } Creates pseudorandom numbers It is part of the java.util class Can be accessed by importing the java.util class Random random = new Random(); For random integer: random.nextInt(); For random integer within a range: random.nextInt(int num); For float: random.nextFloat();
7
JAVA CLASSES AND OBJECTS: MATH CLASS
{ //program calculates the roots of a quadratic equation int a,b,c; double discriminant, root1, root2; //discriminant = (sqrt(b^2 - 4 * a * c)) Scanner scan = new Scanner(System.in); System.out.println("Enter value of a: "); a = scan.nextInt(); System.out.println("Enter value of b: "); b = scan.nextInt(); System.out.println("Enter value of c: "); c = scan.nextInt(); discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant))/(2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant))/(2 * a); System.out.println("Root 1 = " + root1); System.out.println("Root 2 = " + root2); } Provides a large number of basic mathematical functions It is part of the java.lang package All methods in this class are STATIC Some methods include: Math.sqrt(); Math.pow(); Math.ceil(); Math.exp(); Math.random(); Math.floor(); Math.cos(); Math.sin(); Math.tan(); Among many others…
8
NUMBERFORMAT CLASS The NumberFormat class and DecimalFormat class are used to format information in order to display them properly They are both include in the Java standard class library and can be found in the java.text package NumberFormat object does not need to be instantiated using the new keyword Some of its methods include: String Format(double number) : for decimal point formatting NumberFormat.getCurrencyInstance() : for currency formatting NumberFormat.getPercentInstance() : for percentage formatting
9
NumberFormat Class: Example
final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; Scanner scan = new Scanner (System.in); NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance(); System.out.print ("Enter the quantity: "); quantity = scan.nextInt(); System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble(); subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax; // Print output with appropriate formatting System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost));
10
ENUMERATED TYPES This is a special kind of class and the variables of an enumerated types are object variables Enumerated types are type-safe, ensuring invalid values will not be used There is no limit to the number of values that you can list for an enumerated type Once the type is defined, a variable can be declared of that type enum Season = {Summer, Winter, Fall, Spring} Season time; time = Season.Summer; It has two main methods : .ordinal() and .name()
11
WRAPPER CLASSES A wrapper class represents a particular primitive type
A wrapper class allows a primitive value to be managed as an object Integer ageObj = new Integer(40); The ageObj object effectively represents the integer 40 as an object. It can therefore be used wherever an object is required within the program rather than a primitive type They also provide various methods related to the management of the associated primitive type
12
Wrapper Classes: Cont’d
For each primitive type, there exists a corresponding wrapper class in Java Autoboxing: this is the automatic conversion between a primitive value and a corresponding wrapper object Integer obj1; int num1 = 69; Obj1 = num1; //automatically creates an Integer object Integer obj2 = new Integer(62); int num2; num2 = obj2; //automatically extracts the int value Primitive Type Wrapper Class byte Byte short Short int Integer long Long double Double char Character boolean Boolean void Void
13
Object Oriented Programming CONCEPTS
A class is the blueprint of an object A class represents the concept of an object and any object created from that class is a realization of that concept The heart of OOP is defining classes that represent objects with well-defined state and behavior Student public String firstName public String lastName public int Age private bool onProbation Class Attributes or Properties Class Methods or Behavior public Student(fName, lName, Age) public void setProbation(bool probation) public bool getProbation() public String toString()
14
Attributes, Methods and Constructors
Variable names: Public string firstName; //declaration Public string firstName = “John”; //initialization private boolean probation; public string toString(){ return firstName + “ ” + lastName; } //returns a value public void displayName(){ System.out.println(firstName); } //prints directly to screen but returns no value public String setName(String fName){ firstName = fName; }//sets firstName to fName given as a parameter private Boolean getProbation(){ return probation = true; } //private method that returns value of probation attribute Public Student(String Fname, String Lname, int Age){ firstName = Fname; lastName = Lname; age = Age; probation = false; }//the constructor sets initial values for attributes in a new object
15
Encapsulation An object should be encapsulated to guard its data from inappropriate access We should make it difficult, if not impossible, for code outside of a class to “reach in” and change the value of a variable that is declared in that class. This is referred to as ENCAPSULATION Other code should only be able to interact with the class attributes using methods defined by the programmer This is usually achieved using access modifiers
16
Visibility Modifiers Public: can be accessed by other classes. Can be used for both attributes and methods Private: can only be accessed within the class. Can be used for both attributes and methods. Private methods can only be used within the class while private attributes can only be used by methods of the class Protected: Can only be accessed by descendants of the parent class. Can be used for both attributes and methods Constants are usually given public visibility
17
Conditionals and Loops
These allow us to control the flow of execution through a method An if statement allows a program to choose whether to execute a particular statement A loop allows a program to execute a statement multiple times (with the same or different parameters) Loops: while, do and for Conditionals: if, if-else, switch and nested-if
18
Conditionals If-statement: if(height < 10.0)
setAdjustment(0); If-else statement: if(height < 10.0) adjustment = 0; else setAdjustment(10);
19
Comparing Objects The Unicode relationships among characters make it easy to sort characters and strings of characters Using the == or relational operators to compare String objects is highly discouraged; use the .equals(String toCompare) method instead if(name1.equals(name2)) System.out.println(“The names are the same”); else System.out.println(“The names are different”); The compareTo() method can be used to determine the relative order of strings int result = name1.compareTo(name2); If(result < 0) System.out.println(name1 + “ comes before ”+ name2); else if(result == 0) System.out.println(“They are equal”); system.out.println(name2 + “ comes before ”+name1);
20
Loops While statement is a loop that evaluates a boolean condition just as an if statement does and executes a statement (called the body of the loop) if the condition is true while(total > max){ total = total / 2; system.out.println(“Current total: ”+total); } int i = 1; While(i < 5){ System.out.println(i); i++;
21
Break and Continue statements
When a break statement is executed, the flow of execution transfers immediately to the statement after the one governing the current flow The continue statement is similar to break but the loop condition is evaluated again and the loop body is executed again if it is still true
22
ITERATORS An iterator is an object that helps in processing a group of related items The key is that an iterator provides a consistent and simple mechanism for systematically processing a group of items It is closely related to the idea of loops Technically, all iterators use the Iterator interface in java All iterators implement the .hasNext(), .next() methods in various ways An example of an iterator is the scanner class
23
Example of Using Scanner Class as an Iterator for File Reading
String url; Scanner fileScan, urlScan; fileScan = new Scanner (new File("urls.inp")); // Read and process each line of the file while (fileScan.hasNext()) { url = fileScan.nextLine(); System.out.println ("URL: " + url); urlScan = new Scanner (url); urlScan.useDelimiter("/"); // Print each part of the url while (urlScan.hasNext()) System.out.println (" " + urlScan.next()); System.out.println(); }
24
ARRAYLIST This is a very useful class for managing a set of objects in java An ArrayList object stores a list of objects and lets you access them using an integer index When an ArrayList object is created, the programmer specifies the type of element that will be stored in the list ArrayList<String> myNames = new ArrayList<String>(); myNames.add(“Jane”); myNames.add(“Harry”); myNames.add(“Sara”);
25
ArrayList Cont’d Its methods include: .add(E obj)
.remove(int index, E obj) .clear() .contains(object obj) .size() isEmpty() .indexOf(object obj)
26
STATIC VARIABLES A static variable is shared among ALL instances of a class Static variables are sometimes referred to as CLASS VARIABLES There exists only 1 copy of the static variable for all objects of the class Changing the value in one object changes its value in all objects of the class private static int count = 0; Constants, which are declared using the final modifier, are often declared using static modifier
27
STATIC METHODS These are also referred to as class methods
These methods are usually invoked through the class name i.e we don’t have to instantiate an object of the class in order to invoke the method e.g Math.random() A method is made static by using the static modifier in the method declaration e.g public static void main(String[] args) Static methods cannot reference instance variables (which exist only in an instance of a class) Static methods can only reference static variables because they exist independent of specific objects This is why the main method can only access only static or local variables
28
INTERFACES An abstract method is a method that does not have an implementation An interface is a collection of abstract methods and can therefore not be instantiated public interface Complexity { public void setComplexity(int complexity); public void getComplexity(); } Methods in interfaces are all public by default A class that implements an interface uses the keyword implements followed by the interface name in the class header It serves as a “contract” between the interface and class that the class MUST implement all methods declared in the interface A class can have other methods other than those in the interface A class can implement multiple interfaces
29
Contact Us Visit Our Centers: REACH iTech (opposite McAllister’s)
Monday – Thursday: 8am – 8pm Friday: 8am – 4pm (for C, C++, Java, Python) REACH Computer Resource Center (Ekstrom Library) Sunday: 12noon – 2pm (for C#, Access, Excel) Visit Our website:
30
Thank you!!!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.