SlideShare a Scribd company logo
JAVA – J2EE
Programming with Java
History of Java
Java developed by James Gosling in
1990
It took 18 months to develop the first
working version
Introduced with name “AOK”
Again introduce as Java in 1995
Advantage of Java
Simple
Secure
Platform Independent
Object Oriented
Robust
Multithread
Distributed
Hello.java program in Java
File extension should be java
File name and Class name must be same
Class Hello
{
 Public static void main(string a[])
 {
 System.out.println(“Hello !!!”);
 }
}
Public is access modifier
Static is keyword that don’t require to create the instance
of class
Main is entry function
After compilation of java program it
converts in .class file i.e. byte code
Java source code compilation and
execution process
Data Types
Byte 1 byte
Short 2 byte
Int 4 byte
Long 8 byte
Float 4 byte
Double 8 byte
Char 2 byte
Boolean true/false
Global variable
Local variable
Casting
 int a;
 byte b;
 b = (int) a;
Arrays
Controls
If condtion
Switch
Loop – while, do while, for
OOPs
Class
Object
Encapsulation, data abstraction, data
hiding
Constructor
Parameterized constructor
Overloading
Constructor overloading
Static keyword
Final keyword
Finalize method
Inheritance
Overriding
Abstract class
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
Getting and using java
J2SDK freely download from http://java.sun.com
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 (20)

PPTX
Java constructors
QUONTRASOLUTIONS
 
PPTX
C# Arrays
Hock Leng PUAH
 
PDF
Basic Java Programming
Math-Circle
 
PPTX
Data Types, Variables, and Operators
Marwa Ali Eissa
 
PPTX
Introduction to java
Java Lover
 
PPT
Object Oriented Programming with Java
backdoor
 
PPS
Coding Best Practices
mh_azad
 
PDF
Java programming-examples
Mumbai Academisc
 
PPT
Core java concepts
Ram132
 
PPTX
Introduction To C#
rahulsahay19
 
PPT
Final keyword in java
Lovely Professional University
 
PPTX
Constructor in java
Hitesh Kumar
 
PPTX
Python programming
Ashwin Kumar Ramasamy
 
PPTX
Java Introduction
javeed_mhd
 
PDF
C notes.pdf
Durga Padma
 
PPSX
Coding standard
FAROOK Samath
 
PPTX
Java program structure
Mukund Kumar Bharti
 
PPT
Java interfaces
Raja Sekhar
 
Java constructors
QUONTRASOLUTIONS
 
C# Arrays
Hock Leng PUAH
 
Basic Java Programming
Math-Circle
 
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Introduction to java
Java Lover
 
Object Oriented Programming with Java
backdoor
 
Coding Best Practices
mh_azad
 
Java programming-examples
Mumbai Academisc
 
Core java concepts
Ram132
 
Introduction To C#
rahulsahay19
 
Final keyword in java
Lovely Professional University
 
Constructor in java
Hitesh Kumar
 
Python programming
Ashwin Kumar Ramasamy
 
Java Introduction
javeed_mhd
 
C notes.pdf
Durga Padma
 
Coding standard
FAROOK Samath
 
Java program structure
Mukund Kumar Bharti
 
Java interfaces
Raja Sekhar
 

Similar to Java (20)

PPT
Presentation to java
Ganesh Chittalwar
 
PPT
Sep 15
Zia Akbar
 
PPT
Core java Basics
RAMU KOLLI
 
PPT
Sep 15
dilipseervi
 
PPT
Core_java_ppt.ppt
SHIBDASDUTTA
 
PPT
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
PPTX
Java programmingjsjdjdjdjdjdjdjdjdiidiei
rajputtejaswa12
 
PPT
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
nagendrareddy104104
 
PPT
Java Simple Introduction in single course
binzbinz3
 
PPT
Java
Manav Prasad
 
PPT
java01.ppt
Godwin585235
 
PPT
Java
Prabhat gangwar
 
PPTX
Java tutorial for beginners-tibacademy.in
TIB Academy
 
PPT
Present the syntax of Java Introduce the Java
ssuserfd620b
 
PPT
Java PPt.ppt
NavneetSheoran3
 
PPT
java_ notes_for__________basic_level.ppt
amisharawat149
 
PPT
java ppt for basic intro about java and its
kssandhu875
 
PPT
Java - A parent language and powerdul for mobile apps.
dhimananshu130803
 
PPT
Java intro
Sonam Sharma
 
Presentation to java
Ganesh Chittalwar
 
Sep 15
Zia Akbar
 
Core java Basics
RAMU KOLLI
 
Sep 15
dilipseervi
 
Core_java_ppt.ppt
SHIBDASDUTTA
 
Jacarashed-1746968053-300050282-Java.ppt
DilipDas70
 
Java programmingjsjdjdjdjdjdjdjdjdiidiei
rajputtejaswa12
 
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
nagendrareddy104104
 
Java Simple Introduction in single course
binzbinz3
 
java01.ppt
Godwin585235
 
Java tutorial for beginners-tibacademy.in
TIB Academy
 
Present the syntax of Java Introduce the Java
ssuserfd620b
 
Java PPt.ppt
NavneetSheoran3
 
java_ notes_for__________basic_level.ppt
amisharawat149
 
java ppt for basic intro about java and its
kssandhu875
 
Java - A parent language and powerdul for mobile apps.
dhimananshu130803
 
Java intro
Sonam Sharma
 
Ad

More from s4al_com (7)

PPTX
Webservices
s4al_com
 
PPT
Struts
s4al_com
 
PPT
Spring talk111204
s4al_com
 
PPT
Spring
s4al_com
 
PPT
Orm and hibernate
s4al_com
 
PPT
Online gas booking project in java
s4al_com
 
PPTX
Introduction to ejb and struts framework
s4al_com
 
Webservices
s4al_com
 
Struts
s4al_com
 
Spring talk111204
s4al_com
 
Spring
s4al_com
 
Orm and hibernate
s4al_com
 
Online gas booking project in java
s4al_com
 
Introduction to ejb and struts framework
s4al_com
 
Ad

Recently uploaded (20)

PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Dimensions of Societal Planning in Commonism
StefanMz
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 

Java

  • 2. History of Java Java developed by James Gosling in 1990 It took 18 months to develop the first working version Introduced with name “AOK” Again introduce as Java in 1995
  • 3. Advantage of Java Simple Secure Platform Independent Object Oriented Robust Multithread Distributed
  • 4. Hello.java program in Java File extension should be java File name and Class name must be same Class Hello {  Public static void main(string a[])  {  System.out.println(“Hello !!!”);  } } Public is access modifier Static is keyword that don’t require to create the instance of class Main is entry function
  • 5. After compilation of java program it converts in .class file i.e. byte code
  • 6. Java source code compilation and execution process
  • 7. Data Types Byte 1 byte Short 2 byte Int 4 byte Long 8 byte Float 4 byte Double 8 byte Char 2 byte Boolean true/false
  • 8. Global variable Local variable Casting  int a;  byte b;  b = (int) a; Arrays
  • 10. OOPs Class Object Encapsulation, data abstraction, data hiding Constructor Parameterized constructor Overloading Constructor overloading Static keyword
  • 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. Getting and using java J2SDK freely download from http://java.sun.com 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)
  • 15. 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!
  • 16. 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
  • 17. 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.
  • 18. 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
  • 19. 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
  • 20. 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.
  • 21. 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
  • 22. 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
  • 23. 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??
  • 24. Class Person Name: Ke Wang height: 0 weight: 0 Name: Salvatore J. Stolfo height: 0 weight: 0 ke sal
  • 25. Class Person: variables Person x; x=ke; x.printInfo(); x=sal; x.printInfo(); This gives the same output as previous code !
  • 26. Class Person: variables Name: Ke Wang height: 0 weight: 0 Name: Salvatore J. Stolfo height: 0 weight: 0 ke sal x references objects
  • 27. 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)
  • 28. 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
  • 29. 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.
  • 30. 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
  • 31. 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; } }
  • 32. 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!
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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’);
  • 39. 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) {
  • 40. Primitive types - char Char is unsigned type The Character wrapper class has several static methods to work with char, like isDigit(), toUpperCase() etc.
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. 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];
  • 45. 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.
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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!
  • 50. 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
  • 51. 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.
  • 52. 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
  • 53. 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! }
  • 54. 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
  • 55. 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!
  • 56. 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.
  • 57. 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
  • 58. 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
  • 59. 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
  • 60. 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; } }
  • 61. 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
  • 62. 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.
  • 63. 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();
  • 64. Basic exception readLine() throws IOException Required to enclose within try/catch block More on exception later
  • 65. 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