lecture-a-java-review .. this review ppt will help to the lectureres
AshokRachapalli1
17 views
50 slides
Jul 29, 2024
Slide 1 of 50
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
About This Presentation
java
Size: 569.86 KB
Language: en
Added: Jul 29, 2024
Slides: 50 pages
Slide Content
Cmp Sci 187:
Introduction to Java
Based on Appendix A of text
(Koffmann and Wolfgang)
Appendix A: Introduction to Java 2
Topics of the Review
•Essentialsofobject-orientedprogramming,inJava
•Javaprimitivedatatypes,controlstructures,andarrays
•Using some predefined classes:
•Math
•JOptionPane, I/O streams
•String, StringBuffer, StringBuilder
•StringTokenizer
•WritinganddocumentingyourownJavaclasses
Appendix A: Introduction to Java 3
Some Salient Characteristics of Java
•Java is platform independent:the same program can
run on any correctly implemented Java system
•Javaisobject-oriented:
•Structured in terms of classes, which group data with
operations on that data
•Can construct new classes by extendingexisting ones
•Javadesignedas
•A core languageplus
•A rich collection of commonly available packages
•JavacanbeembeddedinWebpages
Appendix A: Introduction to Java 4
Java Processing and Execution
•Begin with Java source codein text files: Model.java
•A Java source code compiler produces Java byte code
•Outputs one file per class:Model.class
•May be standalone or part of an IDE
•A Java Virtual Machineloads and executes class files
•May compile them to native code (e.g., x86) internally
Appendix A: Introduction to Java 5
Compiling and Executing a Java Program
Appendix A: Introduction to Java 6
Classes and Objects
•Theclassistheunitofprogramming
•AJavaprogramisacollectionofclasses
•Each class definition (usually) in its own .javafile
•The file name must match the class name
•Aclassdescribesobjects(instances)
•Describes their common characteristics: is a blueprint
•Thus all the instances have these same characteristics
•Thesecharacteristicsare:
•Data fieldsfor each object
•Methods(operations) that do work on the objects
Appendix A: Introduction to Java 7
Grouping Classes: The Java API
•API = Application Programming Interface
•Java = small core + extensive collection of packages
•A packageconsists of some related Java classes:
•Swing: a GUI (graphical user interface) package
•AWT: Application Window Toolkit (more GUI)
•util: utility data structures (important to CS 187!)
•The importstatement tells the compiler to make
available classes and methods of another package
•A mainmethod indicates where to begin executing a
class (if it is designed to be run as a program)
Appendix A: Introduction to Java 8
A Little Example of importand main
importjavax.swing.*;
//allclassesfromjavax.swing
publicclassHelloWorld{//startsaclass
publicstaticvoidmain(String[]args){
//startsamainmethod
//in:arrayofString;out:none(void)
}
}
•public=canbeseenfromanypackage
•static=not“partof”anobject
Appendix A: Introduction to Java 9
Processing and Running HelloWorld
•javacHelloWorld.java
•Produces HelloWorld.class(byte code)
•javaHelloWorld
•Starts the JVM and runs the mainmethod
Appendix A: Introduction to Java 10
References and Primitive Data Types
•Java distinguishes two kinds of entities
•Primitive types
•Objects
•Primitive-type data is stored in primitive-type variables
•Reference variables store the address ofan object
•No notion of “object (physically) in the stack”
•No notion of “object (physically) within an object”
Appendix A: Introduction to Java 11
Primitive Data Types
•Represent numbers, characters, boolean values
•Integers: byte, short, int, and long
•Real numbers: float and double
•Characters: char
Appendix A: Introduction to Java 12
Primitive Data Types
Data type Range of values
byte -128..127(8bits)
short -32,768..32,767(16bits)
int -2,147,483,648..2,147,483,647(32bits)
long -9,223,372,036,854,775,808.....(64bits)
float +/-10
-38
to+/-10
+38
and0,about6digitsprecision
double +/-10
-308
to+/-10
+308
and0,about15digitsprecision
char Unicodecharacters(generally16bitsperchar)
boolean Trueorfalse
Appendix A: Introduction to Java 13
Primitive Data Types (continued)
Appendix A: Introduction to Java 16
Type Compatibility and Conversion
•Widening conversion:
•In operations on mixed-type operands, the numeric
type of the smaller range is converted to the numeric
type of the larger range
•In an assignment, a numeric type of smaller range
can be assigned to a numeric type of larger range
•bytetoshorttointtolong
•intkind tofloattodouble
Appendix A: Introduction to Java 17
Declaring and Setting Variables
•intsquare;
square=n*n;
•doublecube=n*(double)square;
•Can generally declare local variables where they are
initialized
•All variables get a safe initial value anyway (zero/null)
Appendix A: Introduction to Java 18
Referencing and Creating Objects
•You can declare reference variables
•They reference objects of specified types
•Two reference variables can reference the same object
•The newoperator creates an instance of a class
•A constructorexecutes when a new object is created
•Example: String greeting = ″hello″;
Appendix A: Introduction to Java 19
Java Control Statements
•A group of statements executed in order is written
•{ stmt1; stmt2; ...; stmtN; }
•The statements execute in the order 1, 2, ..., N
•Control statements alter this sequential flow of execution
Appendix A: Introduction to Java 20
Java Control Statements (continued)
Appendix A: Introduction to Java 21
Java Control Statements (continued)
Appendix A: Introduction to Java 22
Methods
•A Java method defines a group of statements as
performing a particular operation
•staticindicates a staticor classmethod
•A method that is not staticis an instancemethod
•All method arguments are call-by-value
•Primitive type: value is passed to the method
•Method may modify local copy butwill not affect
caller’s value
•Object reference: address of objectis passed
•Change to reference variable does not affect caller
•But operations can affect the object, visible to caller
Appendix A: Introduction to Java 23
The Class Math
Appendix A: Introduction to Java 24
Escape Sequences
•An escape sequence is a sequence of two characters
beginning with the character \
•A way to represents special characters/symbols
Appendix A: Introduction to Java 25
The StringClass
•TheStringclassdefinesadatatypethatisusedto
storeasequenceofcharacters
•YoucannotmodifyaStringobject
•If you attempt to do so, Java will create a new object
that contains the modified character sequence
Appendix A: Introduction to Java 26
Comparing Objects
•You can’t use the relational or equality operatorsto
compare the values stored in strings (or other objects)
(You will compare the pointers, not the objects!)
Appendix A: Introduction to Java 27
The StringBufferClass
•Storescharactersequences
•Unlike a Stringobject, you canchange the contentsof
a StringBufferobject
Appendix A: Introduction to Java 28
StringTokenizerClass
•We often need to process individual pieces, or tokens, of
a String
Appendix A: Introduction to Java 29
Wrapper Classes for Primitive Types
•Sometimes we need to process primitive-type data as
objects
•Java provides a set of classes called wrapper classes
whose objects contain primitive-type values: Float,
Double, Integer, Boolean, Character, etc.
Appendix A: Introduction to Java 30
Defining Your Own Classes
•Unified Modeling Language(UML) is a standard diagram
notation for describing a class
Class
name
Field
valuesClass
name
Field
signatures:
type and name
Method signatures:
name, argument
types, result type
Appendix A: Introduction to Java 31
Defining Your Own Classes (continued)
•The modifier privatelimits access to just this class
•Only class members with publicvisibility can be
accessed outside of the class* (* but see protected)
•Constructorsinitialize the data fields of an instance
Appendix A: Introduction to Java 32
The PersonClass
//wehaveomittedjavadoctosavespace
publicclassPerson{
privateStringgivenName;
privateStringfamilyName;
privateStringIDNumber;
privateintbirthYear;
privatestaticfinalintVOTE_AGE=18;
privatestaticfinalintSENIOR_AGE=65;
...
Appendix A: Introduction to Java 34
The PersonClass (3)
//modifierandaccessorforgivenName
publicvoidsetGivenName(Stringgiven){
this.givenName=given;
}
publicStringgetGivenName(){
returnthis.givenName;
}
Appendix A: Introduction to Java 35
The PersonClass (4)
//moreinterestingmethods...
publicintage(intinYear){
returninYear–birthYear;
}
publicbooleancanVote(intinYear){
inttheAge=age(inYear);
returntheAge>=VOTE_AGE;
}
Appendix A: Introduction to Java 36
The PersonClass (5)
//“printing”aPerson
publicStringtoString(){
return“Givenname:“+givenName+“\n”
+“Familyname:“+familyName+“\n”
+“IDnumber:“+IDNumber+“\n”
+“Yearofbirth:“+birthYear+“\n”;
}
Appendix A: Introduction to Java 37
The PersonClass (6)
//samePerson?
publicbooleanequals(Personper){
return(per==null)?false:
this.IDNumber.equals(per.IDNumber);
}
Appendix A: Introduction to Java 38
Arrays
•InJava,anarrayisalsoanobject
•The elements are indexes and are referenced using the
form arrayvar[subscript]
Appendix A: Introduction to Java 39
Array Example
floatgrades[]=newfloat[numStudents];
...grades[student] =something;...
floattotal=0.0;
for(inti=0;i<grades.length;++i){
total+=grades[i];
}
System.out.printf(“Average =%6.2f%n”,
total/numStudents);
Appendix A: Introduction to Java 40
Array Example Variations
//possiblymoreefficient
for(inti=grades.length;--i>=0;){
total+=grades[i];
}
//usesJava5.0“foreach”looping
for(floatgrade:grades){
total+=grade;
}
Appendix A: Introduction to Java 41
Input/Output using Class JOptionPane
•Java 1.2 and higher provide class JOptionPane, which
facilitates display
•Dialog windows for input
•Message windows for output
Appendix A: Introduction to Java 42
Input/Output using Class JOptionPane
(continued)
Appendix A: Introduction to Java 43
Converting Numeric Strings to Numbers
•AdialogwindowalwaysreturnsareferencetoaString
•Therefore,aconversionisrequired,usingstatic
methodsofclassString:
Appendix A: Introduction to Java 44
Input/Output using Streams
•An InputStreamis a sequence of characters
representing program input data
•An OutputStreamis a sequence of characters
representing program output
•The console keyboard stream is System.in
•The console window is associated with System.out
Appendix A: Introduction to Java 45
Opening and Using Files: Reading Input
importjava.io.*;
publicstaticvoidmain(String[]args){
//openaninputstream (**exceptions!)
BufferedReaderrdr=
newBufferedReader(
newFileReader(args[0]));
//readalineofinput
Stringline=rdr.readLine();
//seeifatendoffile
if(line==null){...}
Appendix A: Introduction to Java 46
Opening and Using Files: Reading Input (2)
// using input with StringTokenizer
StringTokenizer sTok =
new StringTokenizer (line);
while (sTok.hasMoreElements()) {
String token = sTok.nextToken();
...;
}
// when done, always close a stream/reader
rdr.close();
Appendix A: Introduction to Java 47
Alternate Ways to Split a String
•UsethesplitmethodofString:
String[] = s.split(“\\s”);
// see class Patternin java.util.regex
•UseaStreamTokenizer(injava.io)
Appendix A: Introduction to Java 48
Opening and Using Files: Writing Output
// open a print stream (**exceptions!)
PrintStream ps = new PrintStream(args[0]);
// ways to write output
ps.print(“Hello”); // a string
ps.print(i+3); // an integer
ps.println(“ and goodbye.”); // with NL
ps.printf(“%2d %12d%n”, i, 1<<i); // like C
ps.format(“%2d %12d%n”, i, 1<<i); // same
// closing output streams is very important!
ps.close();
Appendix A: Introduction to Java 49
Summary of the Review
•A Java program is a collection of classes
•The JVM approach enables a Java program written on
one machine to execute on any other machine that has a
JVM
•Java defines a set of primitive data types that are used
to represent numbers, characters, and boolean data
•The control structures of Java are similar to those found
in other languages
•The Java Stringand StringBufferclasses are used
to reference objects that store character strings
Appendix A: Introduction to Java 50
Chapter Review (continued)
•Be sure to use methods such as equalsand
compareToto compare the contentsof Stringobjects
•You can declare your own Java classes and create
objects of these classes using the newoperator
•A class has data fields and instance methods
•Array variables can reference array objects
•Class JOptionPanecan be used to display dialog
windows for data entry and message windows for output
•The stream classes in package java.ioread strings
from the console and display strings to the console, and
also support file I/O