SlideShare a Scribd company logo
1 of 68
CS3101-3
Programming Language - JAVA
Fall 2004
Sept. 15th
Instructor (and TA)
Ke Wang
604 CEPSR
Web: www.cs.columbia.edu/~kewang
Email: kewang@cs.columbia.edu, or
kw2036@columbia.edu
Tel: 212-646-6076(office)
Office hour: Wed 2pm-4pm(temporary)
About class
Website:
http://www1.cs.columbia.edu/~kewang/cs3101
Meeting time and place:
 Wed. 11am-1pm, 825 Mudd
 Six weeks only, ends at Oct. 20th
Homework
5 or 6 homework
 One homework per week
 All programming
 Goes out every Wed night
 Due next Tuesday 11:59:59pm
 Submission and HW return eletronically
 Grade percentage to be determined
Final?
Late policy
You have one 24-hour extension
Can be used only once
Otherwise, no late homework will be
accepted
Academia Integrity
The work you submit should be
implemented BY YOURSELF
Can get help from me, or friends
Must acknowledge all help given.
Topics to cover
Basic Java, Objects, Classes, Inheritance,
Interfaces, Exceptions, I/O
Applets, GUI Programming, Event
handling
Multithreading, Basic Networking
Packages, Libraries
Some advanced topics, like collections,
database, XML, etc. (If possible)
Textbook
 No required textbook
 Most of the information you need can be found online,
especially at http://java.sun.com
 Tutorials and code camp:
http://java.sun.com/learning/tutorial/index.html
 Java API specification:
http://java.sun.com/j2se/1.4.2/docs/api/index.html
 Important one! Should visit often when coding
Reference books
Core Java 2, Volume I: Fundamentals
Core Java 2, Volume II: Advanced
Features
Thinking in Java, 3rd Edition
 Electronic version available:
http://64.78.49.204/
JAVA in a Nutshell (fourth Edition)
A word about learning a programming
language
PRACTICE
PRACTICE
…
PRACTICE
…
road map today
Brief intro to Java
Develop and compile environment
A simple example
Intro to object/class
Java basics
Differences from C
Intro to Java
 Java programming language
 The one we use to write our program
 Compiled to byte code of JVM
 Java virtual machine (JVM)
 Java interpreter – interpret the compiled byte code
 Software simulated CPU architecture
 Cross-platform: support Linux, Windows, PalmOS…etc.
 Java runtime environment (JRE)
 Predefined set of java classes available to use
 Core Java APIs – basic utilities, I/O, graphics,
network…
Java is portable,
As long as there is a JVM compiled for
that particular processor and OS
Typical program, like C or C++, is
compiled for a particular processor
architecture and OS.
“Write once, run everywhere!”
 Sun’s motto for Java
Bottom line: slow but safe
 Not suitable for high-performance computation
 Scientific computation, games, OS kernel
 Compiled to byte codes of JVM, not native machine
language instructions
 New release of Java is improving the speed a lot
 Just-in-time (JIT) compiler: convert byte codes to native
machine language on the fly
 Very safe
 No pointer
 Automatic garbage collection
 Check array access bound
Java
Java is an object-oriented language, with
a syntax similar to C
 Structured around objects and methods
 A method is an action or something you do with
the object
Avoid those overly complicated features of
C++:
 Operator overloading, pointer, templates, friend
class, etc.
Getting and using java
 J2SDK freely download from http://java.sun.com
 “Your first cup of Java”:
 detailed instructions to help you run your first program
 http://java.sun.com/docs/books/tutorial/getStarted/cupojava/index.h
 All text editors support java
 Vi/vim, emacs, notepad, wordpad
 Just save to .java file
 Have IDEs that comparable to Visual Studio
 JCreator (simple)
 Eclipse (more complicated)
Compile and run an application
Write java class Foo containing a main()
method and save in file “Foo.java”
 The file name MUST be the same as class
name
Compile with: javac Foo.java
Creates compiled .class file: Foo.class
Run the program: java Foo
 Notice: use the class name directly, no .class!
Hello World!
/* Our first Java program – Hello.java */
public class Hello {
//main()
public static void main ( String[] args ) {
System.out.println( "hello world!" );
}
}
File name: Hello.java
Command line
arguments
Standard output, print with new line
About class
Fundamental unit of Java program
All java programs are classes
Each class define a unique kind of object (
a new data type)
Each class defines a set of fields, methods
or other classes
public: modifier. This class is publicly
available and anyone can use it.
Things to notice
Java is case sensitive
whitespace doesn’t matter for compilation
File name must be the same as one of the
class names, including capitalization!
At most one public class per file
If there is one public class in the file, the
filename must be the same as it
Generally one class per file
What is an object?
Object is a thing
An object has state, behavior and identity
 Internal variable: store state
 Method: produce behavior
 Unique address in memory: identity
An object is a manifestation of a class
What is class?
Class introduces a new data type
A class describes a set of objects that
have identical characteristics (data
elements) and behaviors (methods).
 Existing classes provided by JRE
 User defined classes
Once a class is established, you can make
as many objects of it as you like, or none.
Simple example: class Person
A Person has some attributes
The class defines these properties for all
people
Each person gets his own copy of the
fields
Attributes = properties = fields
Class Person: definition
class Person {
String name;
int height; //in inches
int weight; //in pounds
public void printInfo(){
System.out.println(name+" with height="+height+", weight="+weight);
}
}
class ClassName{ /* class body goes here */ }
class: keyword
Class Person: usage
Person ke; //declaration
ke = new Person(); //create an object of Person
ke.name= “Ke Wang”; //access its field
Person sal = new Person();
sal.name=“Salvatore J. Stolfo”;
ke.printInfo();
Sal.printInfo(); // error here??
Class Person
Name: Ke Wang
height: 0
weight: 0
Name: Salvatore J. Stolfo
height: 0
weight: 0
ke
sal
Class Person: variables
Person x;
x=ke;
x.printInfo();
x=sal;
x.printInfo();
This gives the same output as previous code !
Class Person: variables
Name: Ke Wang
height: 0
weight: 0
Name: Salvatore J. Stolfo
height: 0
weight: 0
ke
sal
x
references objects
Reference
 We call x, as well as ke and sal, “reference” to
the object
 Handles to access an object
 Reference itself is not accessible/manipulable
 Different from C/C++, cannot increment/decrement it
 Implemented as pointer+
 Java runtime is watching all assignment to references
 Why? – garbage collection (later)
Reference
Person ke; //only created the reference, not an object.
It points to nothing now (null).
ke = new Person(); //create the object (allocate storage
in memory), and ke is initialized.
ke.name=“Ke Wang”; //access the object through
the reference
More on reference
Have distinguished value null, meaning
pointing to nothing
 if( x==null) { … }
Multiple references can point to one object
When no reference point to an object, that
object is never accessible again.
Class Person: problem
ke.weight = 150; // too bad, but possible
ke.weight = -20; // Houston, we have a problem!!
Need to ensure the validity of value.
Solution: ask the class to do it!
ke.setWeight(150); // OK, now ke’s weight is 150
ke.setWeight(-10); ******** Error, weight must be positive number
Class Person: add method
class Person{
...
void setWeight(int w){
if(w<=0)
System.err.println("***** error, weight must be positive
number! ");
else
weight = w;
}
}
Class Person: new problem
ke.setWeight(-10);
******** Error, weight must be positive number
ke.weight = -20; //haha, I’m the boss!
How about we forgot to use the set function? Or
we just don’t want to?
Solution: just make the variable inaccessible
from outside!
Class Person: private variable
class Person{
private String name;
private int weight;
private int height;
public void setWeight(int w){
if(w<=0)
System.err.println("***** error, weight must be positive
number! ");
else
weight = w;
}
}
Keyword private: no one can access the element except itself
Keyword public: everyone can access the element
Class Person
class Hello{
public static void main ( String[] args ) {
Person ke = new Person();
ke.weight = -20;
}
}
>javac Hello.java
Hello.java:5: weight has private access in Person
ke.weight = -20;
^
1 error
Access functions
Generally make fields private and provide
public getField() and setField() access
functions
O-O term for this is Encapsulation
C# does this by default
Java Basics: primitive types
One group of types get special treatment
in Java
Variable is not created by “new”, not a
reference
Variable holds the value directly
Primitive types
Primitive type Size Minimum Maximum Wrapper type
boolean 1-bit — — Boolean
char 16-bit Unicode 0 Unicode 216
- 1 Character
byte 8-bit -128 +127 Byte
short 16-bit -215
+215
-1 Short
int 32-bit -231
+231
-1 Integer
long 64-bit -263
+263
-1 Long
float 32-bit IEEE754 IEEE754 Float
double 64-bit IEEE754 IEEE754 Double
Primitive types
All numerical types are signed!
 No unsigned keyword in Java
The “wrapper” class allow you to make a
non-primitive object to represent the
primitive one
 char c =‘a’;
 Character C = new Character(c);
 Character C = new Character(‘a’);
Primitive types - boolean
boolean can never convert to or from other
data type, not like C or C++
boolean is not a integer
if(0) doesn’t work in java
Have to explicitly state the comparison
 if( x ==0) {
Primitive types - char
Char is unsigned type
The Character wrapper class has several
static methods to work with char, like
isDigit(), toUpperCase() etc.
Default values for primitive members
 When a primitive type
data is a member of a
class, it’s guaranteed
to get a default value
even if you don’t
initialize it.
 Not true for those
local variables!!
 There will be compile
error if you use it
without initialization
Primitive type Default
boolean false
char ‘u0000’ (null)
byte (byte)0
short (short)0
int 0
long 0L
float 0.0f
double 0.0d
Example
class Hello{
public static void main ( String[] args ) {
int x;
System.out.println(x);
}
}
>javac Hello.java
Hello.java:5: variable x might not have been initialized
System.out.println(x);
^
1 error
Arrays in Java
 An ordered collection of something, addressed
by integer index
 Something can be primitive values, objects, or even
other arrays. But all the values in an array must be of
the same type.
 Only int or char as index
 long values not allowed as array index
 0 based
 Value indexes for array “a” with length 10
 a[0] – a[9];
 a.length==10
 Note: length is an attribute, not method
Arrays in Java: declaration
Declaration
 int[] arr;
 Person[] persons;
 Also support: int arr[]; Person persons[];
(confusing, should be avoided)
Creation
 int[] arr = new int[1024];
 int [][] arr = { {1,2,3}, {4,5,6} };
 Person[] persons = new Person[50];
Arrays in Java: safety
Cannot be accessed outside of its range
 ArrayIndexOutOfBoundsException
Guaranteed to be initialized
 Array of primitive type will be initialized to their
default value
 Zeroes the memory for the array
 Array of objects: actually it’s creating an array
of references, and each of them is initialized to
null.
Arrays in Java:
second kind of reference types in Java
int[] arr = new int [5];
arr
int[][] arr = new int [2][5];
arr[0]
arr[1]
arr
More on reference
 Java doesn’t support & address of , or *, ->
dereference operators.
 reference cannot be converted to or from
integer, cannot be incremented or decremented.
 When you assign an object or array to a
variable, you are actually setting the variable to
hold a reference to that object or array.
 Similarly, you are just passing a reference when
you pass object or array to a method
Reference vs. primitive
 Java handle objects and arrays always by
reference.
 classes and arrays are known as reference types.
 Class and array are composite type, don’t have
standard size
 Java always handle values of the primitive types
directly
 Primitive types have standard size, can be stored in a
fixed amount of memory
 Because of how the primitive types and objects
are handles, they behave different in two areas:
copy value and compare for equality
copy
Primitive types get copied directly by =
 int x= 10; int y=x;
Objects and arrays just copy the
reference, still only one copy of the object
existing.
Name: Ke Wang
height: 0
weight: 0
ke
x
Person ke =new Person();
ke.name="Ke Wang";
Person x=ke;
x.name="Sal";
System.out.println(ke.name); // print Sal!
Compare equality
 Primitive use ==, compare their value directly
int x = 10; int y=10;
if(x==y) { // true !
 Object or array compare their reference, not
content
Person ke =new Person();
ke.name="Ke Wang";
Person ke2 =new Person();
ke2.name="Ke Wang";
if(ke==ke2) //false!!
Person x = ke;
if(ke==x) //true
Copy objects and arrays
 Create new object, then copy all the fields
individually and specifically
 Or write your own copy method in your class
 Or use the special clone() method (inherited by
all objects from java.lang.Object)
int[] data = {1,2,3}; //an array
int[] copy = (int[]) data.clone(); //a copy of the array
Notice: clone() is shallow copy only! The copied object or
array contains all the primitive values and references in the
original one, but won’t clone those references, i.e., not
recursive.
Compare objects and arrays
Write you own comparison method
Or use default equals() method
 All objects inherit equals() from Object, but
default implementation simply uses == for
equality of reference
 Check each class for their definition of equals()
String s = "cs3101";
int num=3101;
String t ="cs"+num;
if(s.equals(t)) { //true!
Notice: + operator also
concatenate string. If either of the
operand to + is a string, the
operator converts the other
operand to a string
Scoping
 Scope determines both the visibility and lifetime
of the names defined within the scope
 Scope is determined by the placement of {},
which is called block.
{
int x = 10;
//only x available
{
int y = 20;
//both x and y available
}
//only x available, y out of scope!
}
Scoping
Notice, you cannot do the following,
although it’s legal in C/C++.
{
int x = 10;
{
int x = 20;
}
}
Compile error
Hello.java:6: x is already defined in
main(java.lang.String[])
int x =20;
^
1 error
Scope of objects
When you create an object using new, the
object hangs around past the end of the
scope, although the reference vanishes.
{
String s = new String("abc");
}
Reference s vanishes, but the String
object still in memory
Solution: Garbage Collector!
Garbage collector
In C++, you have to make sure that you
destroy the objects when you are done
with them.
 Otherwise, memory leak.
In Java, garbage collector do it for you.
 It looks at all the objects created by new and
figure out which ones are no longer being
referenced. Then it release the memory for
those objects.
Importing library
If you need any routines that defined by
java package
import java.util.*;
import java.io.*;
Put at the very beginning of the java file
java.lang.* already been imported.
Check javadoc for the classes
Static keyword
 Want to have only one piece of storage for a
data, regardless how many objects are created,
or even no objects created
 Need a method that isn’t associated with any
particular object of this class
 static keyword apply to both fields and methods
 Can be called directly by class name
 Example: java.lang.Math
 Non-static fields/methods must be called
through an instance
main()
class Hello{
int num;
public static void main(String[] args) {
num = 10;
}
}
>javac Hello.java
Hello.java:4: non-static variable num cannot be referenced
from a static context
num = 10;
^
1 error
Main() doesn’t belong in a class
 Always static
 Because program need a place to start, before any
object been created.
 Poor design decision
 If you need access non-static variable of class
Hello, you need to create object Hello, even if
main() is in class Hello!
class Hello{
int num;
public static void main(String[] args){
Hello h = new Hello();
h.num = 10;
}
}
Difference between C and Java
 No pointers
 No global variable across classes
 Variable declaration anywhere
 Forward reference
 Method can be invoked before defined
 Method overloading
 As long as the methods have different parameter lists
 No struct, union, enum type
 No variable-length argument list
Output
System.out.println();
System.err.println();
 Err corresponds to Unix stderr
System.[out|err].print();
 Same as println(), but no terminating newline
Easy to use, ready to go.
Input: importing library
 Need routines from java.io package
 import java.io.*;
 System.in is not ready to use, need to build a
fully functional input object on top of it
 InputStreamReader(System.in)
 Basic byte-to-char translation
 BufferedReader(InputStreamReader isr)
 Allows us to read in a complete line and return it as a
String
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader(filename));
String line = in.readLine();
Basic exception
readLine() throws IOException
Required to enclose within try/catch block
More on exception later
Integer.parseInt()
Static method
Can take the String returned by readLine()
and spit out an int
Throws NumberFormatException if String
cannot be interpreted as an integer
Question?

More Related Content

What's hot

Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with javaHawkman Academy
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Duckademy IT courses
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Javaagorolabs
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 

What's hot (20)

Core java
Core java Core java
Core java
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Java 101 intro to programming with java
Java 101  intro to programming with javaJava 101  intro to programming with java
Java 101 intro to programming with java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Java basic
Java basicJava basic
Java basic
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...Introduction to Java programming - Java tutorial for beginners to teach Java ...
Introduction to Java programming - Java tutorial for beginners to teach Java ...
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Java
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 

Viewers also liked

basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
Array in Java
Array in JavaArray in Java
Array in JavaAli shah
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of javavinay arora
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2Raghu nath
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the BasicsJussi Pohjolainen
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for DesignersR. Sosa
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1Kevin Rowan
 

Viewers also liked (20)

basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Basic Elements of Java
Basic Elements of JavaBasic Elements of Java
Basic Elements of Java
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Java basics
Java basicsJava basics
Java basics
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
Java basics
Java basicsJava basics
Java basics
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1
 

Similar to Core java Basics

Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.pptbuvanabala
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2miiro30
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Soumen Santra
 
Java Course — Mastering the Fundamentals
Java Course — Mastering the FundamentalsJava Course — Mastering the Fundamentals
Java Course — Mastering the Fundamentalsnehash4637
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
java development companies in Bangalore
java development companies in Bangalorejava development companies in Bangalore
java development companies in BangaloreShreya Anand
 
Java tutorial for beginners-tibacademy.in
Java tutorial for beginners-tibacademy.inJava tutorial for beginners-tibacademy.in
Java tutorial for beginners-tibacademy.inTIB Academy
 
OOPM Introduction.ppt
OOPM Introduction.pptOOPM Introduction.ppt
OOPM Introduction.pptvijay251387
 

Similar to Core java Basics (20)

Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
 
INTRODUCTION TO JAVA
INTRODUCTION TO JAVAINTRODUCTION TO JAVA
INTRODUCTION TO JAVA
 
Java PPt.ppt
Java PPt.pptJava PPt.ppt
Java PPt.ppt
 
java01.ppt
java01.pptjava01.ppt
java01.ppt
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Java
JavaJava
Java
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
Oop java
Oop javaOop java
Oop java
 
core java course online
core java course onlinecore java course online
core java course online
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
 
Java Course — Mastering the Fundamentals
Java Course — Mastering the FundamentalsJava Course — Mastering the Fundamentals
Java Course — Mastering the Fundamentals
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
 
java development companies in Bangalore
java development companies in Bangalorejava development companies in Bangalore
java development companies in Bangalore
 
Java tutorial for beginners-tibacademy.in
Java tutorial for beginners-tibacademy.inJava tutorial for beginners-tibacademy.in
Java tutorial for beginners-tibacademy.in
 
OOPM Introduction.ppt
OOPM Introduction.pptOOPM Introduction.ppt
OOPM Introduction.ppt
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 

Recently uploaded

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 

Recently uploaded (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 

Core java Basics

  • 1. CS3101-3 Programming Language - JAVA Fall 2004 Sept. 15th
  • 2. Instructor (and TA) Ke Wang 604 CEPSR Web: www.cs.columbia.edu/~kewang Email: kewang@cs.columbia.edu, or kw2036@columbia.edu Tel: 212-646-6076(office) Office hour: Wed 2pm-4pm(temporary)
  • 3. About class Website: http://www1.cs.columbia.edu/~kewang/cs3101 Meeting time and place:  Wed. 11am-1pm, 825 Mudd  Six weeks only, ends at Oct. 20th
  • 4. Homework 5 or 6 homework  One homework per week  All programming  Goes out every Wed night  Due next Tuesday 11:59:59pm  Submission and HW return eletronically  Grade percentage to be determined Final?
  • 5. Late policy You have one 24-hour extension Can be used only once Otherwise, no late homework will be accepted
  • 6. Academia Integrity The work you submit should be implemented BY YOURSELF Can get help from me, or friends Must acknowledge all help given.
  • 7. Topics to cover Basic Java, Objects, Classes, Inheritance, Interfaces, Exceptions, I/O Applets, GUI Programming, Event handling Multithreading, Basic Networking Packages, Libraries Some advanced topics, like collections, database, XML, etc. (If possible)
  • 8. Textbook  No required textbook  Most of the information you need can be found online, especially at http://java.sun.com  Tutorials and code camp: http://java.sun.com/learning/tutorial/index.html  Java API specification: http://java.sun.com/j2se/1.4.2/docs/api/index.html  Important one! Should visit often when coding
  • 9. Reference books Core Java 2, Volume I: Fundamentals Core Java 2, Volume II: Advanced Features Thinking in Java, 3rd Edition  Electronic version available: http://64.78.49.204/ JAVA in a Nutshell (fourth Edition)
  • 10. A word about learning a programming language PRACTICE PRACTICE … PRACTICE …
  • 11. road map today Brief intro to Java Develop and compile environment A simple example Intro to object/class Java basics Differences from C
  • 12. Intro to Java  Java programming language  The one we use to write our program  Compiled to byte code of JVM  Java virtual machine (JVM)  Java interpreter – interpret the compiled byte code  Software simulated CPU architecture  Cross-platform: support Linux, Windows, PalmOS…etc.  Java runtime environment (JRE)  Predefined set of java classes available to use  Core Java APIs – basic utilities, I/O, graphics, network…
  • 13. Java is portable, As long as there is a JVM compiled for that particular processor and OS Typical program, like C or C++, is compiled for a particular processor architecture and OS. “Write once, run everywhere!”  Sun’s motto for Java
  • 14. Bottom line: slow but safe  Not suitable for high-performance computation  Scientific computation, games, OS kernel  Compiled to byte codes of JVM, not native machine language instructions  New release of Java is improving the speed a lot  Just-in-time (JIT) compiler: convert byte codes to native machine language on the fly  Very safe  No pointer  Automatic garbage collection  Check array access bound
  • 15. Java Java is an object-oriented language, with a syntax similar to C  Structured around objects and methods  A method is an action or something you do with the object Avoid those overly complicated features of C++:  Operator overloading, pointer, templates, friend class, etc.
  • 16. Getting and using java  J2SDK freely download from http://java.sun.com  “Your first cup of Java”:  detailed instructions to help you run your first program  http://java.sun.com/docs/books/tutorial/getStarted/cupojava/index.h  All text editors support java  Vi/vim, emacs, notepad, wordpad  Just save to .java file  Have IDEs that comparable to Visual Studio  JCreator (simple)  Eclipse (more complicated)
  • 17. Compile and run an application Write java class Foo containing a main() method and save in file “Foo.java”  The file name MUST be the same as class name Compile with: javac Foo.java Creates compiled .class file: Foo.class Run the program: java Foo  Notice: use the class name directly, no .class!
  • 18. Hello World! /* Our first Java program – Hello.java */ public class Hello { //main() public static void main ( String[] args ) { System.out.println( "hello world!" ); } } File name: Hello.java Command line arguments Standard output, print with new line
  • 19. About class Fundamental unit of Java program All java programs are classes Each class define a unique kind of object ( a new data type) Each class defines a set of fields, methods or other classes public: modifier. This class is publicly available and anyone can use it.
  • 20. Things to notice Java is case sensitive whitespace doesn’t matter for compilation File name must be the same as one of the class names, including capitalization! At most one public class per file If there is one public class in the file, the filename must be the same as it Generally one class per file
  • 21. What is an object? Object is a thing An object has state, behavior and identity  Internal variable: store state  Method: produce behavior  Unique address in memory: identity An object is a manifestation of a class
  • 22. What is class? Class introduces a new data type A class describes a set of objects that have identical characteristics (data elements) and behaviors (methods).  Existing classes provided by JRE  User defined classes Once a class is established, you can make as many objects of it as you like, or none.
  • 23. Simple example: class Person A Person has some attributes The class defines these properties for all people Each person gets his own copy of the fields Attributes = properties = fields
  • 24. Class Person: definition class Person { String name; int height; //in inches int weight; //in pounds public void printInfo(){ System.out.println(name+" with height="+height+", weight="+weight); } } class ClassName{ /* class body goes here */ } class: keyword
  • 25. Class Person: usage Person ke; //declaration ke = new Person(); //create an object of Person ke.name= “Ke Wang”; //access its field Person sal = new Person(); sal.name=“Salvatore J. Stolfo”; ke.printInfo(); Sal.printInfo(); // error here??
  • 26. Class Person Name: Ke Wang height: 0 weight: 0 Name: Salvatore J. Stolfo height: 0 weight: 0 ke sal
  • 27. Class Person: variables Person x; x=ke; x.printInfo(); x=sal; x.printInfo(); This gives the same output as previous code !
  • 28. Class Person: variables Name: Ke Wang height: 0 weight: 0 Name: Salvatore J. Stolfo height: 0 weight: 0 ke sal x references objects
  • 29. Reference  We call x, as well as ke and sal, “reference” to the object  Handles to access an object  Reference itself is not accessible/manipulable  Different from C/C++, cannot increment/decrement it  Implemented as pointer+  Java runtime is watching all assignment to references  Why? – garbage collection (later)
  • 30. Reference Person ke; //only created the reference, not an object. It points to nothing now (null). ke = new Person(); //create the object (allocate storage in memory), and ke is initialized. ke.name=“Ke Wang”; //access the object through the reference
  • 31. More on reference Have distinguished value null, meaning pointing to nothing  if( x==null) { … } Multiple references can point to one object When no reference point to an object, that object is never accessible again.
  • 32. Class Person: problem ke.weight = 150; // too bad, but possible ke.weight = -20; // Houston, we have a problem!! Need to ensure the validity of value. Solution: ask the class to do it! ke.setWeight(150); // OK, now ke’s weight is 150 ke.setWeight(-10); ******** Error, weight must be positive number
  • 33. Class Person: add method class Person{ ... void setWeight(int w){ if(w<=0) System.err.println("***** error, weight must be positive number! "); else weight = w; } }
  • 34. Class Person: new problem ke.setWeight(-10); ******** Error, weight must be positive number ke.weight = -20; //haha, I’m the boss! How about we forgot to use the set function? Or we just don’t want to? Solution: just make the variable inaccessible from outside!
  • 35. Class Person: private variable class Person{ private String name; private int weight; private int height; public void setWeight(int w){ if(w<=0) System.err.println("***** error, weight must be positive number! "); else weight = w; } } Keyword private: no one can access the element except itself Keyword public: everyone can access the element
  • 36. Class Person class Hello{ public static void main ( String[] args ) { Person ke = new Person(); ke.weight = -20; } } >javac Hello.java Hello.java:5: weight has private access in Person ke.weight = -20; ^ 1 error
  • 37. Access functions Generally make fields private and provide public getField() and setField() access functions O-O term for this is Encapsulation C# does this by default
  • 38. Java Basics: primitive types One group of types get special treatment in Java Variable is not created by “new”, not a reference Variable holds the value directly
  • 39. Primitive types Primitive type Size Minimum Maximum Wrapper type boolean 1-bit — — Boolean char 16-bit Unicode 0 Unicode 216 - 1 Character byte 8-bit -128 +127 Byte short 16-bit -215 +215 -1 Short int 32-bit -231 +231 -1 Integer long 64-bit -263 +263 -1 Long float 32-bit IEEE754 IEEE754 Float double 64-bit IEEE754 IEEE754 Double
  • 40. Primitive types All numerical types are signed!  No unsigned keyword in Java The “wrapper” class allow you to make a non-primitive object to represent the primitive one  char c =‘a’;  Character C = new Character(c);  Character C = new Character(‘a’);
  • 41. Primitive types - boolean boolean can never convert to or from other data type, not like C or C++ boolean is not a integer if(0) doesn’t work in java Have to explicitly state the comparison  if( x ==0) {
  • 42. Primitive types - char Char is unsigned type The Character wrapper class has several static methods to work with char, like isDigit(), toUpperCase() etc.
  • 43. Default values for primitive members  When a primitive type data is a member of a class, it’s guaranteed to get a default value even if you don’t initialize it.  Not true for those local variables!!  There will be compile error if you use it without initialization Primitive type Default boolean false char ‘u0000’ (null) byte (byte)0 short (short)0 int 0 long 0L float 0.0f double 0.0d
  • 44. Example class Hello{ public static void main ( String[] args ) { int x; System.out.println(x); } } >javac Hello.java Hello.java:5: variable x might not have been initialized System.out.println(x); ^ 1 error
  • 45. Arrays in Java  An ordered collection of something, addressed by integer index  Something can be primitive values, objects, or even other arrays. But all the values in an array must be of the same type.  Only int or char as index  long values not allowed as array index  0 based  Value indexes for array “a” with length 10  a[0] – a[9];  a.length==10  Note: length is an attribute, not method
  • 46. Arrays in Java: declaration Declaration  int[] arr;  Person[] persons;  Also support: int arr[]; Person persons[]; (confusing, should be avoided) Creation  int[] arr = new int[1024];  int [][] arr = { {1,2,3}, {4,5,6} };  Person[] persons = new Person[50];
  • 47. Arrays in Java: safety Cannot be accessed outside of its range  ArrayIndexOutOfBoundsException Guaranteed to be initialized  Array of primitive type will be initialized to their default value  Zeroes the memory for the array  Array of objects: actually it’s creating an array of references, and each of them is initialized to null.
  • 48. Arrays in Java: second kind of reference types in Java int[] arr = new int [5]; arr int[][] arr = new int [2][5]; arr[0] arr[1] arr
  • 49. More on reference  Java doesn’t support & address of , or *, -> dereference operators.  reference cannot be converted to or from integer, cannot be incremented or decremented.  When you assign an object or array to a variable, you are actually setting the variable to hold a reference to that object or array.  Similarly, you are just passing a reference when you pass object or array to a method
  • 50. Reference vs. primitive  Java handle objects and arrays always by reference.  classes and arrays are known as reference types.  Class and array are composite type, don’t have standard size  Java always handle values of the primitive types directly  Primitive types have standard size, can be stored in a fixed amount of memory  Because of how the primitive types and objects are handles, they behave different in two areas: copy value and compare for equality
  • 51. copy Primitive types get copied directly by =  int x= 10; int y=x; Objects and arrays just copy the reference, still only one copy of the object existing. Name: Ke Wang height: 0 weight: 0 ke x Person ke =new Person(); ke.name="Ke Wang"; Person x=ke; x.name="Sal"; System.out.println(ke.name); // print Sal!
  • 52. Compare equality  Primitive use ==, compare their value directly int x = 10; int y=10; if(x==y) { // true !  Object or array compare their reference, not content Person ke =new Person(); ke.name="Ke Wang"; Person ke2 =new Person(); ke2.name="Ke Wang"; if(ke==ke2) //false!! Person x = ke; if(ke==x) //true
  • 53. Copy objects and arrays  Create new object, then copy all the fields individually and specifically  Or write your own copy method in your class  Or use the special clone() method (inherited by all objects from java.lang.Object) int[] data = {1,2,3}; //an array int[] copy = (int[]) data.clone(); //a copy of the array Notice: clone() is shallow copy only! The copied object or array contains all the primitive values and references in the original one, but won’t clone those references, i.e., not recursive.
  • 54. Compare objects and arrays Write you own comparison method Or use default equals() method  All objects inherit equals() from Object, but default implementation simply uses == for equality of reference  Check each class for their definition of equals() String s = "cs3101"; int num=3101; String t ="cs"+num; if(s.equals(t)) { //true! Notice: + operator also concatenate string. If either of the operand to + is a string, the operator converts the other operand to a string
  • 55. Scoping  Scope determines both the visibility and lifetime of the names defined within the scope  Scope is determined by the placement of {}, which is called block. { int x = 10; //only x available { int y = 20; //both x and y available } //only x available, y out of scope! }
  • 56. Scoping Notice, you cannot do the following, although it’s legal in C/C++. { int x = 10; { int x = 20; } } Compile error Hello.java:6: x is already defined in main(java.lang.String[]) int x =20; ^ 1 error
  • 57. Scope of objects When you create an object using new, the object hangs around past the end of the scope, although the reference vanishes. { String s = new String("abc"); } Reference s vanishes, but the String object still in memory Solution: Garbage Collector!
  • 58. Garbage collector In C++, you have to make sure that you destroy the objects when you are done with them.  Otherwise, memory leak. In Java, garbage collector do it for you.  It looks at all the objects created by new and figure out which ones are no longer being referenced. Then it release the memory for those objects.
  • 59. Importing library If you need any routines that defined by java package import java.util.*; import java.io.*; Put at the very beginning of the java file java.lang.* already been imported. Check javadoc for the classes
  • 60. Static keyword  Want to have only one piece of storage for a data, regardless how many objects are created, or even no objects created  Need a method that isn’t associated with any particular object of this class  static keyword apply to both fields and methods  Can be called directly by class name  Example: java.lang.Math  Non-static fields/methods must be called through an instance
  • 61. main() class Hello{ int num; public static void main(String[] args) { num = 10; } } >javac Hello.java Hello.java:4: non-static variable num cannot be referenced from a static context num = 10; ^ 1 error
  • 62. Main() doesn’t belong in a class  Always static  Because program need a place to start, before any object been created.  Poor design decision  If you need access non-static variable of class Hello, you need to create object Hello, even if main() is in class Hello! class Hello{ int num; public static void main(String[] args){ Hello h = new Hello(); h.num = 10; } }
  • 63. Difference between C and Java  No pointers  No global variable across classes  Variable declaration anywhere  Forward reference  Method can be invoked before defined  Method overloading  As long as the methods have different parameter lists  No struct, union, enum type  No variable-length argument list
  • 64. Output System.out.println(); System.err.println();  Err corresponds to Unix stderr System.[out|err].print();  Same as println(), but no terminating newline Easy to use, ready to go.
  • 65. Input: importing library  Need routines from java.io package  import java.io.*;  System.in is not ready to use, need to build a fully functional input object on top of it  InputStreamReader(System.in)  Basic byte-to-char translation  BufferedReader(InputStreamReader isr)  Allows us to read in a complete line and return it as a String BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader(filename)); String line = in.readLine();
  • 66. Basic exception readLine() throws IOException Required to enclose within try/catch block More on exception later
  • 67. Integer.parseInt() Static method Can take the String returned by readLine() and spit out an int Throws NumberFormatException if String cannot be interpreted as an integer