JAVA
Course Objectives
Upon completing the course, you will understand
–Create, compile, and run Java programs
–Develop programs using Eclipse
–Write simple programs using primitive data types, control
statements, methods, and arrays.
–Core Java classes (Swing, exception, multithreading, I/O,
networking, Java Collections Framework)
–Develop a GUI interface and Java applets
Chapters - overview
Part I: Fundamentals of Programming
Chapter 1 Introduction to Java
Chapter 2 Primitive Data Types and Operations
Chapter 3 Control Statements
Chapter 4 Methods
Chapter 5 Arrays
Part II: Object-Oriented Programming
Chapter 6 Objects and Classes
Chapter 7 Strings
Chapter 8 Class Inheritance and Interfaces
Chapter 9 Object-Oriented Software Development
Part III: GUI Programming
Chapter 10 Getting Started with GUI Programming
Chapter 11 Creating User Interfaces
Chapter 12 Applets and Advanced GUI
Part IV: Developing Comprehensive Projects
Chapter 13 Exception Handling
Chapter 14 Internationalization
Chapter 15 Multithreading
Chapter 16 Multimedia
Chapter 17 Input and Output
Chapter 18 Networking
Chapter 19 Java Data Structures
Introduction
Evolved into write once run anywhere
Platform independent
JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone
applications or applets.
Java Enterprise Edition (J2EE)
J2EE can be used to develop server-side applications such as
Java servlets and Java ServerPages.
For business applications, web services, mission-critical
systems, Transaction processing, databases, distribution.
Java Micro Edition (J2ME).
J2ME can be used to develop applications for mobile devices
such as cell phones.
Very small Java environment for smart cards, pages, phones,
and set-top boxes
Subset of the standard Java libraries aimed at limited size and
processing power
Java Development Kit
javac - The Java Compiler
java - The Java Interpreter
jdb - The Java Debugger
appletviewer -Tool to run the applets
javap - to print the Java byte codes
javadoc - documentation generator
javah - creates C header files
Java IDE Tools
Forte by Sun MicroSystems
Borland JBuilder
Microsoft Visual J++
WebGain Café
IBM Visual Age for Java
Netbeans (Sun)
JBuilder (Borland)
Eclipse (IBM and others)
Characteristics of Java
Portable - Write Once, Run Anywhere
Security has been well thought through
Robust memory management
Designed for network programming
Multi-threaded (multiple simultaneous tasks)
Dynamic & extensible (loads of libraries)
Classes stored in separate files
Loaded only when needed
The Virtual Machine
Java is both compiled and interpreted
Source code is compiled into Java bytecode
Which is then interpreted by the Java Virtual Machine
(JVM)
Therefore bytecode is machine code for the JVM
Java bytecode can run on any JVM, on any
platform
…including mobile phones and other hand-held devices
Networking and distribution are core features
In other languages these are additional APIs
Makes Java very good for building networked
applications, server side components, etc.
Jacarashed-1746968053-300050282-Java.ppt
Object-Oriented Programming
Understanding OOP is fundamental to writing good Java
applications
Improves design of your code
Improves understanding of the Java APIs
There are several concepts underlying OOP:
Abstract Types (Classes)
Encapsulation (or Information Hiding)
Inheritance
Polymorphism
How to get it running
Type the file and save it as filename.java
To compile:
javac filename.java
To run / execute:
java classname
Note:
Java is CASE SENSITIVE!!
Whitespace is ignored by compiler.
For public class File name has to be the same as class name in
file.
First Application
Welcome.java
public class Welcome
{
public static void main (String args[])
{
System.out.println ("Welcome to Java
programming");
} //end main
} //end class
Anatomy of a Java Program
Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
Comments
When the compiler sees comments, it ignores text
// text
The compiler ignores everything from // to the end of the line
/* text */
The compiler ignores everything from /* to */.
/** documentation */
Documentation comments allow you to embed information
about your program into the program itself. You can then use the
javadoc utility program to extract the information and put it into an
HTML file.
Eg: /** * This class calculates CGPA.
* @author Myname
* @version 1.2 */
javadoc filename.java
Variables
all variables must be declared before they can be used
Local variables
Instance variables
Class/static variables
Variables:
Type
Name
Value
Naming:
May contain numbers, underscore, dollar sign, or letters
Can not start with number
Can be any length
Reserved keywords
Case sensitive
Scoping
As in C/C++, scope is determined by the placement of
curly braces {}.
A variable defined within a scope is available only to the
end of that scope.
{ int x = 12;
/* only x available */
{ int q = 96;
/* both x and q available */
}
/* only x available */
/* q “out of scope” */
}
{ int x = 12;
{ int x = 96; /* illegal */
}
}
This is ok in C/C++ but not in Java.
Methods, arguments and return values
Java methods are like C/C++ functions. General case:
returnType methodName ( arg1, arg2, … argN) {
methodBody
}
The return keyword exits a method optionally with a value
int storage(String s) {return s.length() * 2;}
boolean flag() { return true; }
float naturalLogBase() { return 2.718f; }
void nothing() { return; }
void nothing2() {}
Primitive data types
Byte 8 -27
27-1
Short 16 -215
215
-1
Int 32 -231
231
-1
Long 64
Float 32
Double 64
Boolean 1 0 1
Char 16
Strings
Not a primitive class, its actually something called a wrapper class
To find a built in class’s method use API documentation.
String is a group of char’s
A character has single quotes
char c = ‘h’;
A String has double quotes
String s = “Hello World”;
Method length
int n = s.length;
public class hello{
public static void main (String [] args) {
String s = “Hello Worldn”;
System.out.println(s); //output simple string
} //end main
}//end class hello
Reserved Words
Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other
purposes in the program. For example, when the compiler
sees the word class, it understands that the word after class
is the name for the class. Other reserved words are public,
static, and void. Their use will be introduced later in the
book.
Modifiers
Java uses certain reserved words called modifiers
that specify the properties of the data, methods, and
classes and how they can be used. Examples of
modifiers are public and static. Other modifiers are
private, final, abstract, and protected. A public
datum, method, or class can be accessed by other
programs. A private datum or method cannot be
accessed by other programs. Modifiers are discussed
in Chapter 6, "Objects and Classes."
Statements
A simple statement is a command terminated by a semi-
colon:
name = “Fred”;
A block is a compound statement enclosed in curly brackets:
{
name1 = “Fred”; name2 = “Bill”;
}
Blocks may contain other blocks
public class Test {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Class block
Method block
Classes
• The class is the essential Java construct. A class is a template or
blueprint for objects.
An example of a class
class Person { Variable
String name;
int age; Method
void birthday ( )
{
age++;
System.out.println (name +
' is now ' + age);
}
}
Extending a class
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r); // Invoke the constructor of the superclass, Circle()
this.cx = x; // Initialize the instance field cx
this.cy = y; // Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy; // Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r); // Returns true or false
}
}
main Method
The main method provides the control of program flow. when you
execute a class with the Java interpreter, the runtime system starts by
calling the class's main() method. .
The main method looks like this:
public static void main(String[] args) {
// Statements;
}
• The main() method is static because they can then be invoked by the
runtime engine without having to create an instance of the class.
•The modifiers public and static can be written in either order (public
static or static public), but the convention is to use public static as
shown above. You can name the argument anything you want, but
most programmers choose "args" or "argv“
•The main method accepts a single argument: an array of elements of
type String
System.out.println:
• println is a method in the PrintStream class.
• out is a static final variable in System class which is of the type
PrintStream (a built-in class, contains methods to print the different
data values).
• out here denotes the reference variable of the type PrintStream
class.
• static fields and methods must be accessed by using the class
name, so ( System.out ).
• println() is a public method in PrintStream class to print the data
values.
Overloading, overwriting, and shadowing
Overloading occurs when Java can distinguish two procedures
with the same name by examining the number or types of their
parameters.
Shadowing or overriding occurs when two procedures with the
same signature (name, the same number of parameters, and the
same parameter types) are defined in different classes, one of
which is a super class of the other.
Access control
Access to packages
Java offers no control mechanisms for packages.
If you can find and read the package you can access it
Access to classes
All top level classes in package P are accessible anywhere in P
All public top-level classes in P are accessible anywhere
Access to class members (in class C in package P)
Public: accessible anywhere C is accessible
Protected: accessible in P and to any of C’s subclasses
Private: only accessible within class C
Package: only accessible in P (the default)
Jacarashed-1746968053-300050282-Java.ppt
The static keyword
Java methods and variables can be declared static
These exist independent of any object
This means that a Class’s
static methods can be called even if no objects of that class have been
created
static data is “shared” by all instances (i.e., one value per class instead
of one per instance
class StaticTest {static int i = 47;}
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
// st1.i == st2.I == 47
StaticTest.i++; // or st1.I++ or st2.I++
// st1.i == st2.I == 48
public class Circle {
// A class field
public static final double PI= 3.14159; // A useful constant
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads * 180 / PI;
}
// An instance field
public double r; // The radius of the circle
// Two methods which operate on the instance fields of an object
public double area() { // Compute the area of the circle
return PI * r * r;
}
public double circumference() { // Compute the circumference of the circle
return 2 * PI * r;
}
}
Abstract classes and methods
Abstract vs. concrete classes
Abstract classes can not be instantiated
public abstract class shape { }
An abstract method is a method w/o a body
public abstract double area();
(Only) Abstract classes can have abstract methods
In fact, any class with an abstract method is automatically an
abstract class
Example
abstract class
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference();// semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class Rectangle extends Shape {
protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods.
}
Displaying Text in a Message Dialog Box
you can use the showMessageDialog method in
the JOptionPane class. JOptionPane is one of the
many predefined classes in the Java system,
which can be reused rather than “reinventing the
wheel.”
Run
Source
showMessageDialog Method
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
"Example 1.2",
JOptionPane.INFORMATION_MESSAGE));
Flow of Control
 Java executes one statement after the other in the order
they are written
 Many Java statements are flow control statements:
Alternation: if, if else, switch
Looping: for, while, do while
Escapes: break, continue, return
If… else
The if … else statement evaluates an expression
and performs one action if that evaluation is true
or a different action if it is false.
if (x != oldx) {
System.out.print(“x was changed”);
}
else {
System.out.print(“x is unchanged”);
}
Nested if … else
if ( myVal > 100 ) {
if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(“myVal is in range”);
}
else if
Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed,
execute code block #3
}
A Warning…
WRONG!
if( i == j )
if ( j == k )
System.out.print(
“i equals k”);
else
System.out.print(
“i is not equal
to j”);
CORRECT!
if( i == j ) {
if ( j == k )
System.out.print(
“i equals
k”);
}
else
System.out.print(
“i is not equal
to j”); //
Correct!
The switch Statement
switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then
//execute code block #4
break;
}
The for loop
Loop n times
for ( i = 0; i < n; n++ ) {
// this code body will execute n times
// ifrom 0 to n-1
}
Nested for:
for ( j = 0; j < 10; j++ ) {
for ( i = 0; i < 20; i++ ){
// this code body will execute 200
times
}
}
while loops
while(response == 1) {
System.out.print( “ID =” + userID[n]);
n++;
response = readInt( “Enter “);
}
What is the minimum number of times the loop
is executed?
What is the maximum number of times?
do {… } while loops
do {
System.out.print( “ID =” + userID[n] );
n++;
response = readInt( “Enter ” );
}while (response == 1);
What is the minimum number of times the loop
is executed?
What is the maximum number of times?
Break
A break statement causes an exit from
the innermost containing while, do, for or
switch statement.
for ( int i = 0; i < maxID, i++ )
{
if ( userID[i] == targetID ) {
index = i;
break;
}
} // program jumps here after break
Continue
Can only be used with while, do or for.
The continue statement causes the innermost loop
to start the next iteration immediately
for ( int i = 0; i < maxID; i++ ) {
if ( userID[i] != -1 ) continue;
System.out.print( “UserID ” + i + “ :” +
userID);
}
Arrays
An array is a list of similar things
An array has a fixed:
name
type
length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution of the
code
myArray has room for 8 elements
the elements are accessed by their index
in Java, array indices start at 0
3 6 3 1 6 3 4 1
myArray =
0 1 2 3 4 5 6 7
Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled myArray[0] to
myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
Assigning Values
refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
Iterating Through Arrays
for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length;i++) {
myArray[i] = getsomevalue();
}
Arrays of Objects
So far we have looked at an array of primitive types.
Integers & could also use doubles, floats,
characters…
Often want to have an array of objects
Students, Books, Loans ……
Need to follow 3 steps.
1. Declare the array
private Student studentList[];
– this declares studentList
2 .Create the array
studentList = new Student[10];
– this sets up 10 spaces in memory that can hold
references to Student objects
3. Create Student objects and add them to the array:
studentList[0] = new Student("Cathy",
"Computing");
Declaring the Array
1. Declare the array
private Student studentList[];
this declares studentList
2 .Create the array
studentList = new Student[10];
this sets up 10 spaces in memory that
can hold references to Student objects
3. Create Student objects and add them to the
array: studentList[0] = new
Student("Cathy", "Computing");
Constructors
Classes should define one or more methods to create or construct
instances of the class
Their name is the same as the class name
note deviation from convention that methods begin with lower case
Constructors are differentiated by the number and types of their
arguments
An example of overloading
If you don’t define a constructor, a default one will be created.
Constructors automatically invoke the zero argument constructor of
their superclass when they begin (note that this yields a recursive
process!)
Exceptions
Java exception object.
java.io.Exception
most general one.
Some exception like in Throwable class define methods to get the
message.
System.exit()
One method in java.lang.System
Defined:
public static void exit ( int status)
Terminates currently running Java VM
Status is status code, non zero will usually mean something
abnormal.
Used at end to indicate success, or in middle to signal problems.
Echo.java
drive:path> type echo.java
// This is the Echo example from the Sun tutorial
class echo {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
System.out.println( args[i] );
}
}
}
drive:path>javac echo.java
drive:path> java echo this is pretty silly
this
is
pretty
silly
Syntax Notes
No global variables
class variables and methods may be applied to any instance of
an object
methods may have local (private?) variables
No pointers
but complex data objects are “referenced”
Other parts of Java are borrowed from PL/I, Modula, and other
languages
Useful Resources
Useful resources on the web
Java home (http://java.sun.com)
Articles, Software and document downloads, Tutorials
Java Developer Services
http://developer.java.sun.com
Early access downloads, forums, newsletters, bug database
Javaworld (http://www.javaworld.com)
Java magazine site, good set of articles and tutorials
IBM developerWorks
(http://www.ibm.com/developerWorks)
Technology articles and tutorials
Object class
Super class of all java classes
System.out.println()
println is a method in the PrintStream class.
out is a static final variable in System class which is of the type
PrintStream (a built-in class, contains methods to print the different
data values).
out here denotes the reference variable of the type PrintStream class.
static fields and methods must be accessed by using the class name,
so ( System.out ).
println() is a public method in PrintStream class to print the data
values.
class System
{
public static PrintWriter out;
}
class PrintWriter
{
println()
{
}
}
String Comparison
String strVal= “polytechnic”
String strVal1= “polytechnic”
== true
Equals true
(String strVal1= strVal)
String strVal= “polytechnic”
String strVal1= new String(“polytechnic”)
== false
Equals true
String strVal= new String(“polytechnic”)
String strVal1= new String(“polytechnic”)
== false
Equals true
Abstract
Methods wont have implementation – overridden by
sub class
Cant create objects to abstract class
Can create reference
All methods inside abstract class should be abstract
Cannot use final and abstract keyword at a time
final
Method – cannot be overridden
Class – cannot be inherited
Variable – constant
If a class is declared as final, all methods inside classes
are final default
Interfaces
All variables are constant
All methods are abstract and public – no concrete
methods
If a class implements a interface, the class should
override all the methods in the interface
A class implements more than one interfaces, it should
give implementation to all methods in all interfaces
static
Class variables / methods
For static variables, only one time memory is allocated
irrespective of creating objects.
Non static variables, memory will be allocated for
every time creating objects for class
Inside static methods cannot access non static members.
Can access only static variables and methods
Singleton class
Create only one object
using private constructor
Static Initializer
Initial value to static member inside static initializer
A class file enter into memory when a object is created
or static method is called.
Instance Initializer
When creating object for the class, instance initializer
will be executed
Constructor
Called when object is created
Provide initial value to data members
Wont return any value
If we don’t keep any constructor inside class, run time
system will provide constructor with out args.
Jacarashed-1746968053-300050282-Java.ppt

More Related Content

PPT
java01.ppt
PPT
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
PPT
Java Simple Introduction in single course
PPTX
Java programmingjsjdjdjdjdjdjdjdjdiidiei
PPT
Java PPt.ppt
PPTX
Java tutorial for beginners-tibacademy.in
PPT
JAVA ppt tutorial basics to learn java programming
PPT
java01.ppt
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
Java Simple Introduction in single course
Java programmingjsjdjdjdjdjdjdjdjdiidiei
Java PPt.ppt
Java tutorial for beginners-tibacademy.in
JAVA ppt tutorial basics to learn java programming

Similar to Jacarashed-1746968053-300050282-Java.ppt (20)

PPT
java_ notes_for__________basic_level.ppt
PPT
java ppt for basic intro about java and its
PPT
Java intro
PPT
Java01
PPT
Java01
PPT
Java - A parent language and powerdul for mobile apps.
PPT
Present the syntax of Java Introduce the Java
PPT
java-corporate-training-institute-in-mumbai
PPT
java-corporate-training-institute-in-mumbai
PPTX
object oriented programming unit one ppt
PPTX
Introduction to JcjfjfjfkuutyuyrsdterdfbvAVA.pptx
PPTX
mukul Dubey.pptx
PPT
java01.ppt
PPT
java01.ppt
PPT
java01.ppt
PPT
java01.ppt
PPT
java01.ppt
PPT
java01.ppt
PPT
OOPs concept and java Environment decsion making statement looping array and ...
java_ notes_for__________basic_level.ppt
java ppt for basic intro about java and its
Java intro
Java01
Java01
Java - A parent language and powerdul for mobile apps.
Present the syntax of Java Introduce the Java
java-corporate-training-institute-in-mumbai
java-corporate-training-institute-in-mumbai
object oriented programming unit one ppt
Introduction to JcjfjfjfkuutyuyrsdterdfbvAVA.pptx
mukul Dubey.pptx
java01.ppt
java01.ppt
java01.ppt
java01.ppt
java01.ppt
java01.ppt
OOPs concept and java Environment decsion making statement looping array and ...
Ad

Recently uploaded (20)

PDF
Concepts of Database Management, 10th Edition by Lisa Friedrichsen Test Bank.pdf
PPTX
Overview_of_Computing_Presentation.pptxxx
PPTX
cyber row.pptx for cyber proffesionals and hackers
PPTX
Basic Statistical Analysis for experimental data.pptx
PPT
Technicalities in writing workshops indigenous language
PDF
book-34714 (2).pdfhjkkljgfdssawtjiiiiiujj
PPTX
langchainpptforbeginners_easy_explanation.pptx
PPTX
Sheep Seg. Marketing Plan_C2 2025 (1).pptx
PDF
9 FinOps Tools That Simplify Cloud Cost Reporting.pdf
PDF
American Journal of Multidisciplinary Research and Review
PPT
What is life? We never know the answer exactly
PDF
Nucleic-Acids_-Structure-Typ...-1.pdf 011
PPTX
Capstone Presentation a.pptx on data sci
PPTX
Bussiness Plan S Group of college 2020-23 Final
PDF
Teal Blue Futuristic Metaverse Presentation.pdf
PPTX
lung disease detection using transfer learning approach.pptx
PDF
NU-MEP-Standards معايير تصميم جامعية .pdf
PDF
Book Trusted Companions in Delhi – 24/7 Available Delhi Personal Meeting Ser...
PPTX
DATA ANALYTICS COURSE IN PITAMPURA.pptx
PDF
2025-08 San Francisco FinOps Meetup: Tiering, Intelligently.
Concepts of Database Management, 10th Edition by Lisa Friedrichsen Test Bank.pdf
Overview_of_Computing_Presentation.pptxxx
cyber row.pptx for cyber proffesionals and hackers
Basic Statistical Analysis for experimental data.pptx
Technicalities in writing workshops indigenous language
book-34714 (2).pdfhjkkljgfdssawtjiiiiiujj
langchainpptforbeginners_easy_explanation.pptx
Sheep Seg. Marketing Plan_C2 2025 (1).pptx
9 FinOps Tools That Simplify Cloud Cost Reporting.pdf
American Journal of Multidisciplinary Research and Review
What is life? We never know the answer exactly
Nucleic-Acids_-Structure-Typ...-1.pdf 011
Capstone Presentation a.pptx on data sci
Bussiness Plan S Group of college 2020-23 Final
Teal Blue Futuristic Metaverse Presentation.pdf
lung disease detection using transfer learning approach.pptx
NU-MEP-Standards معايير تصميم جامعية .pdf
Book Trusted Companions in Delhi – 24/7 Available Delhi Personal Meeting Ser...
DATA ANALYTICS COURSE IN PITAMPURA.pptx
2025-08 San Francisco FinOps Meetup: Tiering, Intelligently.
Ad

Jacarashed-1746968053-300050282-Java.ppt

  • 2. Course Objectives Upon completing the course, you will understand –Create, compile, and run Java programs –Develop programs using Eclipse –Write simple programs using primitive data types, control statements, methods, and arrays. –Core Java classes (Swing, exception, multithreading, I/O, networking, Java Collections Framework) –Develop a GUI interface and Java applets
  • 3. Chapters - overview Part I: Fundamentals of Programming Chapter 1 Introduction to Java Chapter 2 Primitive Data Types and Operations Chapter 3 Control Statements Chapter 4 Methods Chapter 5 Arrays Part II: Object-Oriented Programming Chapter 6 Objects and Classes Chapter 7 Strings Chapter 8 Class Inheritance and Interfaces Chapter 9 Object-Oriented Software Development Part III: GUI Programming Chapter 10 Getting Started with GUI Programming Chapter 11 Creating User Interfaces Chapter 12 Applets and Advanced GUI Part IV: Developing Comprehensive Projects Chapter 13 Exception Handling Chapter 14 Internationalization Chapter 15 Multithreading Chapter 16 Multimedia Chapter 17 Input and Output Chapter 18 Networking Chapter 19 Java Data Structures
  • 4. Introduction Evolved into write once run anywhere Platform independent
  • 5. JDK Editions Java Standard Edition (J2SE) J2SE can be used to develop client-side standalone applications or applets. Java Enterprise Edition (J2EE) J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages. For business applications, web services, mission-critical systems, Transaction processing, databases, distribution. Java Micro Edition (J2ME). J2ME can be used to develop applications for mobile devices such as cell phones. Very small Java environment for smart cards, pages, phones, and set-top boxes Subset of the standard Java libraries aimed at limited size and processing power
  • 6. Java Development Kit javac - The Java Compiler java - The Java Interpreter jdb - The Java Debugger appletviewer -Tool to run the applets javap - to print the Java byte codes javadoc - documentation generator javah - creates C header files
  • 7. Java IDE Tools Forte by Sun MicroSystems Borland JBuilder Microsoft Visual J++ WebGain Café IBM Visual Age for Java Netbeans (Sun) JBuilder (Borland) Eclipse (IBM and others)
  • 8. Characteristics of Java Portable - Write Once, Run Anywhere Security has been well thought through Robust memory management Designed for network programming Multi-threaded (multiple simultaneous tasks) Dynamic & extensible (loads of libraries) Classes stored in separate files Loaded only when needed
  • 9. The Virtual Machine Java is both compiled and interpreted Source code is compiled into Java bytecode Which is then interpreted by the Java Virtual Machine (JVM) Therefore bytecode is machine code for the JVM Java bytecode can run on any JVM, on any platform …including mobile phones and other hand-held devices Networking and distribution are core features In other languages these are additional APIs Makes Java very good for building networked applications, server side components, etc.
  • 11. Object-Oriented Programming Understanding OOP is fundamental to writing good Java applications Improves design of your code Improves understanding of the Java APIs There are several concepts underlying OOP: Abstract Types (Classes) Encapsulation (or Information Hiding) Inheritance Polymorphism
  • 12. How to get it running Type the file and save it as filename.java To compile: javac filename.java To run / execute: java classname Note: Java is CASE SENSITIVE!! Whitespace is ignored by compiler. For public class File name has to be the same as class name in file.
  • 13. First Application Welcome.java public class Welcome { public static void main (String args[]) { System.out.println ("Welcome to Java programming"); } //end main } //end class
  • 14. Anatomy of a Java Program Comments Package Reserved words Modifiers Statements Blocks Classes Methods The main method
  • 15. Comments When the compiler sees comments, it ignores text // text The compiler ignores everything from // to the end of the line /* text */ The compiler ignores everything from /* to */. /** documentation */ Documentation comments allow you to embed information about your program into the program itself. You can then use the javadoc utility program to extract the information and put it into an HTML file. Eg: /** * This class calculates CGPA. * @author Myname * @version 1.2 */ javadoc filename.java
  • 16. Variables all variables must be declared before they can be used Local variables Instance variables Class/static variables Variables: Type Name Value Naming: May contain numbers, underscore, dollar sign, or letters Can not start with number Can be any length Reserved keywords Case sensitive
  • 17. Scoping As in C/C++, scope is determined by the placement of curly braces {}. A variable defined within a scope is available only to the end of that scope. { int x = 12; /* only x available */ { int q = 96; /* both x and q available */ } /* only x available */ /* q “out of scope” */ } { int x = 12; { int x = 96; /* illegal */ } } This is ok in C/C++ but not in Java.
  • 18. Methods, arguments and return values Java methods are like C/C++ functions. General case: returnType methodName ( arg1, arg2, … argN) { methodBody } The return keyword exits a method optionally with a value int storage(String s) {return s.length() * 2;} boolean flag() { return true; } float naturalLogBase() { return 2.718f; } void nothing() { return; } void nothing2() {}
  • 19. Primitive data types Byte 8 -27 27-1 Short 16 -215 215 -1 Int 32 -231 231 -1 Long 64 Float 32 Double 64 Boolean 1 0 1 Char 16
  • 20. Strings Not a primitive class, its actually something called a wrapper class To find a built in class’s method use API documentation. String is a group of char’s A character has single quotes char c = ‘h’; A String has double quotes String s = “Hello World”; Method length int n = s.length; public class hello{ public static void main (String [] args) { String s = “Hello Worldn”; System.out.println(s); //output simple string } //end main }//end class hello
  • 21. Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Other reserved words are public, static, and void. Their use will be introduced later in the book.
  • 22. Modifiers Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other programs. A private datum or method cannot be accessed by other programs. Modifiers are discussed in Chapter 6, "Objects and Classes."
  • 23. Statements A simple statement is a command terminated by a semi- colon: name = “Fred”; A block is a compound statement enclosed in curly brackets: { name1 = “Fred”; name2 = “Bill”; } Blocks may contain other blocks public class Test { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } Class block Method block
  • 24. Classes • The class is the essential Java construct. A class is a template or blueprint for objects.
  • 25. An example of a class class Person { Variable String name; int age; Method void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } }
  • 26. Extending a class public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle, // so we only have to put the new stuff here. // New instance fields that store the center point of the circle public double cx, cy; // A new constructor method to initialize the new fields // It uses a special syntax to invoke the Circle() constructor public PlaneCircle(double r, double x, double y) { super(r); // Invoke the constructor of the superclass, Circle() this.cx = x; // Initialize the instance field cx this.cy = y; // Initialize the instance field cy } // The area() and circumference() methods are inherited from Circle // A new instance method that checks whether a point is inside the circle // Note that it uses the inherited instance field r public boolean isInside(double x, double y) { double dx = x - cx, dy = y - cy; // Distance from center double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem return (distance < r); // Returns true or false } }
  • 27. main Method The main method provides the control of program flow. when you execute a class with the Java interpreter, the runtime system starts by calling the class's main() method. . The main method looks like this: public static void main(String[] args) { // Statements; } • The main() method is static because they can then be invoked by the runtime engine without having to create an instance of the class. •The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv“ •The main method accepts a single argument: an array of elements of type String
  • 28. System.out.println: • println is a method in the PrintStream class. • out is a static final variable in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values). • out here denotes the reference variable of the type PrintStream class. • static fields and methods must be accessed by using the class name, so ( System.out ). • println() is a public method in PrintStream class to print the data values.
  • 29. Overloading, overwriting, and shadowing Overloading occurs when Java can distinguish two procedures with the same name by examining the number or types of their parameters. Shadowing or overriding occurs when two procedures with the same signature (name, the same number of parameters, and the same parameter types) are defined in different classes, one of which is a super class of the other.
  • 30. Access control Access to packages Java offers no control mechanisms for packages. If you can find and read the package you can access it Access to classes All top level classes in package P are accessible anywhere in P All public top-level classes in P are accessible anywhere Access to class members (in class C in package P) Public: accessible anywhere C is accessible Protected: accessible in P and to any of C’s subclasses Private: only accessible within class C Package: only accessible in P (the default)
  • 32. The static keyword Java methods and variables can be declared static These exist independent of any object This means that a Class’s static methods can be called even if no objects of that class have been created static data is “shared” by all instances (i.e., one value per class instead of one per instance class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.I == 47 StaticTest.i++; // or st1.I++ or st2.I++ // st1.i == st2.I == 48
  • 33. public class Circle { // A class field public static final double PI= 3.14159; // A useful constant // A class method: just compute a value based on the arguments public static double radiansToDegrees(double rads) { return rads * 180 / PI; } // An instance field public double r; // The radius of the circle // Two methods which operate on the instance fields of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference of the circle return 2 * PI * r; } }
  • 34. Abstract classes and methods Abstract vs. concrete classes Abstract classes can not be instantiated public abstract class shape { } An abstract method is a method w/o a body public abstract double area(); (Only) Abstract classes can have abstract methods In fact, any class with an abstract method is automatically an abstract class
  • 35. Example abstract class public abstract class Shape { public abstract double area(); // Abstract methods: note public abstract double circumference();// semicolon instead of body. } class Circle extends Shape { public static final double PI = 3.14159265358979323846; protected double r; // Instance data public Circle(double r) { this.r = r; } // Constructor public double getRadius() { return r; } // Accessor public double area() { return PI*r*r; } // Implementations of public double circumference() { return 2*PI*r; } // abstract methods. } class Rectangle extends Shape { protected double w, h; // Instance data public Rectangle(double w, double h) { // Constructor this.w = w; this.h = h; } public double getWidth() { return w; } // Accessor method public double getHeight() { return h; } // Another accessor public double area() { return w*h; } // Implementations of public double circumference() { return 2*(w + h); } // abstract methods. }
  • 36. Displaying Text in a Message Dialog Box you can use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.” Run Source
  • 37. showMessageDialog Method JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2", JOptionPane.INFORMATION_MESSAGE));
  • 38. Flow of Control  Java executes one statement after the other in the order they are written  Many Java statements are flow control statements: Alternation: if, if else, switch Looping: for, while, do while Escapes: break, continue, return
  • 39. If… else The if … else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false. if (x != oldx) { System.out.print(“x was changed”); } else { System.out.print(“x is unchanged”); }
  • 40. Nested if … else if ( myVal > 100 ) { if ( remainderOn == true) { myVal = mVal % 100; } else { myVal = myVal / 100.0; } } else { System.out.print(“myVal is in range”); }
  • 41. else if Useful for choosing between alternatives: if ( n == 1 ) { // execute code block #1 } else if ( j == 2 ) { // execute code block #2 } else { // if all previous tests have failed, execute code block #3 }
  • 42. A Warning… WRONG! if( i == j ) if ( j == k ) System.out.print( “i equals k”); else System.out.print( “i is not equal to j”); CORRECT! if( i == j ) { if ( j == k ) System.out.print( “i equals k”); } else System.out.print( “i is not equal to j”); // Correct!
  • 43. The switch Statement switch ( n ) { case 1: // execute code block #1 break; case 2: // execute code block #2 break; default: // if all previous tests fail then //execute code block #4 break; }
  • 44. The for loop Loop n times for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n-1 } Nested for: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } }
  • 45. while loops while(response == 1) { System.out.print( “ID =” + userID[n]); n++; response = readInt( “Enter “); } What is the minimum number of times the loop is executed? What is the maximum number of times?
  • 46. do {… } while loops do { System.out.print( “ID =” + userID[n] ); n++; response = readInt( “Enter ” ); }while (response == 1); What is the minimum number of times the loop is executed? What is the maximum number of times?
  • 47. Break A break statement causes an exit from the innermost containing while, do, for or switch statement. for ( int i = 0; i < maxID, i++ ) { if ( userID[i] == targetID ) { index = i; break; } } // program jumps here after break
  • 48. Continue Can only be used with while, do or for. The continue statement causes the innermost loop to start the next iteration immediately for ( int i = 0; i < maxID; i++ ) { if ( userID[i] != -1 ) continue; System.out.print( “UserID ” + i + “ :” + userID); }
  • 49. Arrays An array is a list of similar things An array has a fixed: name type length These must be declared when the array is created. Arrays sizes cannot be changed during the execution of the code myArray has room for 8 elements the elements are accessed by their index in Java, array indices start at 0 3 6 3 1 6 3 4 1 myArray = 0 1 2 3 4 5 6 7
  • 50. Declaring Arrays int myArray[]; declares myArray to be an array of integers myArray = new int[8]; sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7] int myArray[] = new int[8]; combines the two statements in one line Assigning Values refer to the array elements by index to store values in them. myArray[0] = 3; myArray[1] = 6; myArray[2] = 3; ... can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1}; Iterating Through Arrays for loops are useful when dealing with arrays: for (int i = 0; i < myArray.length;i++) { myArray[i] = getsomevalue(); }
  • 51. Arrays of Objects So far we have looked at an array of primitive types. Integers & could also use doubles, floats, characters… Often want to have an array of objects Students, Books, Loans …… Need to follow 3 steps. 1. Declare the array private Student studentList[]; – this declares studentList 2 .Create the array studentList = new Student[10]; – this sets up 10 spaces in memory that can hold references to Student objects 3. Create Student objects and add them to the array: studentList[0] = new Student("Cathy", "Computing");
  • 52. Declaring the Array 1. Declare the array private Student studentList[]; this declares studentList 2 .Create the array studentList = new Student[10]; this sets up 10 spaces in memory that can hold references to Student objects 3. Create Student objects and add them to the array: studentList[0] = new Student("Cathy", "Computing");
  • 53. Constructors Classes should define one or more methods to create or construct instances of the class Their name is the same as the class name note deviation from convention that methods begin with lower case Constructors are differentiated by the number and types of their arguments An example of overloading If you don’t define a constructor, a default one will be created. Constructors automatically invoke the zero argument constructor of their superclass when they begin (note that this yields a recursive process!)
  • 54. Exceptions Java exception object. java.io.Exception most general one. Some exception like in Throwable class define methods to get the message.
  • 55. System.exit() One method in java.lang.System Defined: public static void exit ( int status) Terminates currently running Java VM Status is status code, non zero will usually mean something abnormal. Used at end to indicate success, or in middle to signal problems.
  • 56. Echo.java drive:path> type echo.java // This is the Echo example from the Sun tutorial class echo { public static void main(String args[]) { for (int i=0; i < args.length; i++) { System.out.println( args[i] ); } } } drive:path>javac echo.java drive:path> java echo this is pretty silly this is pretty silly
  • 57. Syntax Notes No global variables class variables and methods may be applied to any instance of an object methods may have local (private?) variables No pointers but complex data objects are “referenced” Other parts of Java are borrowed from PL/I, Modula, and other languages
  • 58. Useful Resources Useful resources on the web Java home (http://java.sun.com) Articles, Software and document downloads, Tutorials Java Developer Services http://developer.java.sun.com Early access downloads, forums, newsletters, bug database Javaworld (http://www.javaworld.com) Java magazine site, good set of articles and tutorials IBM developerWorks (http://www.ibm.com/developerWorks) Technology articles and tutorials
  • 59. Object class Super class of all java classes
  • 60. System.out.println() println is a method in the PrintStream class. out is a static final variable in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values). out here denotes the reference variable of the type PrintStream class. static fields and methods must be accessed by using the class name, so ( System.out ). println() is a public method in PrintStream class to print the data values. class System { public static PrintWriter out; } class PrintWriter { println() { } }
  • 61. String Comparison String strVal= “polytechnic” String strVal1= “polytechnic” == true Equals true (String strVal1= strVal) String strVal= “polytechnic” String strVal1= new String(“polytechnic”) == false Equals true String strVal= new String(“polytechnic”) String strVal1= new String(“polytechnic”) == false Equals true
  • 62. Abstract Methods wont have implementation – overridden by sub class Cant create objects to abstract class Can create reference All methods inside abstract class should be abstract Cannot use final and abstract keyword at a time
  • 63. final Method – cannot be overridden Class – cannot be inherited Variable – constant If a class is declared as final, all methods inside classes are final default
  • 64. Interfaces All variables are constant All methods are abstract and public – no concrete methods If a class implements a interface, the class should override all the methods in the interface A class implements more than one interfaces, it should give implementation to all methods in all interfaces
  • 65. static Class variables / methods For static variables, only one time memory is allocated irrespective of creating objects. Non static variables, memory will be allocated for every time creating objects for class Inside static methods cannot access non static members. Can access only static variables and methods
  • 66. Singleton class Create only one object using private constructor
  • 67. Static Initializer Initial value to static member inside static initializer A class file enter into memory when a object is created or static method is called. Instance Initializer When creating object for the class, instance initializer will be executed
  • 68. Constructor Called when object is created Provide initial value to data members Wont return any value If we don’t keep any constructor inside class, run time system will provide constructor with out args.