This document provides an overview of key concepts in the Java programming language including classes, objects, inheritance, interfaces, packages, exceptions, threads, and more. It discusses how to build standalone Java programs and applets, and covers basic syntax and structures like primitive data types, expressions, control statements, and comments. Methods, constructors, and access modifiers are also explained at a high level.
2. Introduction
ο Present the syntax of Java
ο Introduce the Java API
ο Demonstrate how to build
ο stand-alone Java programs
ο Java applets, which run within browsers e.g. Netscape
ο Example programs
7decret.com 2
3. Why Java?
ο Itβs almost entirely object-oriented
ο It has a vast library of predefined objects and
operations
ο Itβs more platform independent
ο this makes it great for Web programming
ο Itβs more secure
ο Open Source
7decret.com 3
4. Building Standalone JAVA
Programs
ο Prepare the file foo.java using an editor
ο Invoke the compiler: javac foo.java
ο This creates foo.class
ο Run the java interpreter: java foo
7decret.com 4
5. Java Virtual Machine
ο The .class files generated by the compiler are not
executable binaries
ο so Java combines compilation and interpretation
ο Instead, they contain βbyte-codesβ to be executed by
the Java Virtual Machine
ο other languages have done this, e.g. UCSD Pascal
ο This approach provides platform independence, and
greater security
7decret.com 5
6. HelloWorld (standalone)
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
ο Note that String is built in
ο println is a member function for the System.out
class
7decret.com 6
7. Comments are almost like C++
ο /* This kind of comment can span multiple lines */
ο // This kind is to the end of the line
ο /**
* This kind of comment is a special
* βjavadocβ style comment
*/
7decret.com 7
8. Primitive data types are like C
ο Main data types are int, double, boolean, char
ο Also have byte, short, long, float
ο boolean has values true and false
ο Declarations look like C, for example,
ο double x, y;
ο int count = 0;
7decret.com 8
9. Expressions are like C
ο Assignment statements mostly look like those in C;
you can use =, +=, *= etc.
ο Arithmetic uses the familiar + - * / %
ο Java also has ++ and --
ο Java has boolean operators && || !
ο Java has comparisons < <= == != >= >
ο Java does not have pointers or pointer arithmetic
7decret.com 9
10. Control statements are like C
ο if (x < y) smaller = x;
ο if (x < y){ smaller=x;sum += x;}
else { smaller = y; sum += y; }
ο while (x < y) { y = y - x; }
ο do { y = y - x; } while (x < y)
ο for (int i = 0; i < max; i++)
ο sum += i;
ο BUT: conditions must be boolean !
7decret.com 10
11. Control statements II
switch (n + 1) {
case 0: m = n - 1; break;
case 1: m = n + 1;
case 3: m = m * n; break;
default: m = -n; break;
}
ο Java also introduces the try statement, about which
more later
7decret.com 11
12. Java isn't C!
ο In C, almost everything is in functions
ο In Java, almost everything is in classes
ο There is often only one class per file
ο There must be only one public class per file
ο The file name must be the same as the name of that
public class, but with a .java extension
7decret.com 12
13. Java program layout
ο A typical Java file looks like:
Package asdf ;
import java.awt.*;
import java.util.*;
public class SomethingOrOther {
// object definitions go here
...
must be in a file named SomethingOrOther.java !
This }
7decret.com 13
14. What is a class?
ο Early languages had only arrays
ο all elements had to be of the same type
ο Then languages introduced structures (called
records, or structs)
ο allowed different data types to be grouped
7decret.com 14
15. So, what is a class?
ο A class consists of
ο a collection of fields, or variables, very much like the
named fields of a struct
ο all the operations (called methods) that can be
performed on those fields
ο can be instantiated
ο A class describes objects and operations defined on
those objects
7decret.com 15
16. Name conventions
ο Java is case-sensitive; maxval, maxVal, and MaxVal are
three different names
ο Class names begin with a capital letter
ο All other names begin with a lowercase letter
ο Subsequent words are capitalized: theBigOne
ο Underscores are not used in names
ο These are very strong conventions!
7decret.com 16
17. The class hierarchy
ο Classes are arranged in a hierarchy
ο The root, or topmost, class is Object
ο Every class but Object has at least one superclass
ο A class may have subclasses
ο Each class inherits all the fields and methods of its
(possibly numerous) superclasses
7decret.com 17
18. An example of a class
class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name + ' is now ' + age);
}
}
7decret.com 18
19. Another example of a class
class Driver extends Person {
long driversLicenseNumber;
Date expirationDate;
}
7decret.com 19
20. Creating and using an object
ο Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
ο Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
7decret.com 20
21. An array is an object
ο Person mary = new Person ( );
ο int myArray[ ] = new int[5];
ο or:
ο int myArray[ ] = {1, 4, 9, 16, 25};
ο String languages [ ] = {"Prolog", "Java"};
7decret.com 21
22. Applets and Servlets
ο An applet is designed to be embedded in a Web
page, and run by a browser
ο A servlet is designed to be run by a web server
7decret.com 22
25. Static keyword
ο Instance methods are associated with an object and
use the instance variables of that object. This is the
default. A servlet is designed to be run by a web server
ο Static methods use no instance variables of any
object of the class they are defined in.(Security reason)
ο Can only call from static method.
7decret.com 25
26. Final Keyword
ο You can declare some or all of a class's methods
final. You use the final keyword in a method
declaration to indicate that the method cannot be
overridden by subclasses.
ο Methods called from constructors should generally
be declared final.
ο Note that you can also declare an entire class final
β this prevents the class from being subclassed.
7decret.com 26
28. Public
ο Fields, methods and constructors declared public
(least restrictive) within a public class are visible to any
class in the Java program, whether these classes are in
the same package or in another package.
7decret.com 28
29. Private
ο The private (most restrictive) fields or methods cannot
be used for classes and Interfaces.
ο It also cannot be used for fields and methods within an
interface.
ο they cannot be accesses by anywhere outside the
enclosing class
7decret.com 29
30. Protected
ο The protected fields or methods cannot be used for
classes and Interfaces.
ο It also cannot be used for fields and methods within an
interface.
ο methods and constructors declared protected in a
superclass can be accessed only by subclasses in other
packages.
7decret.com 30
31. Protected Cont..
ο Classes in the same package can also access protected
fields, methods and constructors as well, even if they
are not a subclass of the protected memberβs class.
7decret.com 31
32. Default
ο Java provides a default specifier which is used when
no access modifier is present.
ο Any class, field, method or constructor that has no
declared access modifier is accessible only by
classes in the same package.
ο The default modifier is not used for fields and
methods within an interface.
7decret.com 32
33. Inheritance
ο Inheritance is a compile-time mechanism in Java
that allows you to extend a class (called the base
class or superclass ) with another class (called the
derived class or subclass).
7decret.com 33
34. Types of Inheritance
ο Single Inheritance
ο Multi Level Inheritance
ο Hierarchicval Inheritance
7decret.com 34
39. Interfaces
ο An interface is a group of related methods with
empty bodies.
ο Implement all method of interface otherwise class
become abstract
ο functions are public and abstract
ο fields are public and final .
7decret.com 39
40. Abstract Class
ο An abstract class is a class that is declared
abstractβit may or may not include abstract
methods.
ο Abstract classes cannot be instantiated, but they
can be subclassed.
7decret.com 40
41. Abstract method
ο An abstract method is a method that is declared
without an implementation (without braces, and
followed by a semicolon)
ο If a class includes abstract methods, the class itself
must be declared abstract.
7decret.com 41
42. Abstract method cont..
ο When an abstract class is subclassed, the subclass
usually provides implementations for all of the
abstract methods in its parent class. However, if it
does not, the subclass must also be declared
abstract.
7decret.com 42
44. Dynamic Method Dispatch
ο Dynamic method dispatch is the mechanism by
which a call to an overridden method is resolved at
run time, rather than compile time.
ο Dynamic method dispatch is important because
this is how Java implements run-time
polymorphism.
7decret.com 44
46. Dynamic Method Dispatch
ο Dynamic method dispatch is the mechanism by
which a call to an overridden method is resolved at
run time, rather than compile time.
ο Dynamic method dispatch is important because
this is how Java implements run-time
polymorphism.
7decret.com 46
47. Package
ο A package is a grouping of related types providing
access protection and name space management.
7decret.com 47
48. Creating a package
ο To create a package, you choose a name for the
package and put a package statement with that
name at the top of every source file that contains
the types (classes, interfaces, enumerations, and
annotation types) that you want to include in the
package.
7decret.com 48
49. Name Convention
ο Package names are written in all lowercase to avoid
conflict with the names of classes or interfaces.
7decret.com 49
50. Exception
ο Exception is a run-time error which arises during
the execution of java program. The term exception
in java stands for an exceptional event.
7decret.com 50
52. Exception
ο Exception is a run-time error which arises during
the execution of java program. The term exception
in java stands for an exceptional event.
7decret.com 52
53. Thread
ο A thread is a thread of execution in a program.
ο The Java Virtual Machine allows an application to
have multiple threads of execution running
concurrently.
7decret.com 53
54. Run() method
ο When a thread is created, it must be permanently
bound to an object with a run() method. When the
thread is started, it will invoke the object's run()
method. More specifically, the object must implement
the Runnable interface.
7decret.com 54
55. Extending thread class
ο By creating thread class(extend thread class)
ο By concerting a class into thread(implementing a
runnable interface)
7decret.com 55
56. Extending the thread class
ο Extend a thread class
ο Implement the run() method
ο Create a thread object and call the start method.
7decret.com 56
57. Lifecycle of Thread
ο Multithreading refers to two or more tasks executing
concurrently within a single program.Many threads
can run concurrently within a program. Every thread
in Java is created and controlled by the
java.lang.Thread class. A Java program can have
many threads, and these threads can run
concurrently, either asynchronously or synchronously.
7decret.com 57
60. Multithreading
ο Multithreading refers to two or more tasks executing
concurrently within a single program.Many threads
can run concurrently within a program. Every thread
in Java is created and controlled by the
java.lang.Thread class. A Java program can have
many threads, and these threads can run
concurrently, either asynchronously or synchronously.
7decret.com 60
61. States
ο New state β After the creations of Thread instance
the thread is in this state but before the start()
method invocation. At this point, the thread is
considered not alive.
7decret.com 61
62. States
ο Runnable (Ready-to-run) state β A thread start its
life from Runnable state. A thread first enters
runnable state after the invoking of start() method
but a thread can return to this state after either
running, waiting, sleeping or coming back from
blocked state also. On this state a thread is waiting for
a turn on the processor.
7decret.com 62
63. States
ο Running state β A thread is in running state that
means the thread is currently executing. There are
several ways to enter in Runnable state but there is
only one way to enter in Running state: the scheduler
select a thread from runnable pool.
7decret.com 63
64. States
ο Dead state β A thread can be considered dead when
its run() method completes. If any thread comes on
this state that means it cannot ever run again.
7decret.com 64
65. States
ο Blocked - A thread can enter in this state because of
waiting the resources that are hold by another thread.
7decret.com 65
66. Thread Exception
ο Sleep method must be in try catch block
ο IllegalThreadStateExceprtion(Whenever we
invoke the method not in given state)
ο InterruptedException
ο IllegalArgumentException
7decret.com 66
68. Inter-Thread Communication
ο A process where, a thread is paused running in its
critical region and another thread is allowed to enter
(or lock) in the same critical section to be
executed. This technique is known as Interthread
communication which is implemented by some
methods.
ο These methods are defined in "java.lang" package
7decret.com 68
70. Thread Exception
ο Sleep method must be in try catch block
ο IllegalThreadStateExceprtion(Whenever we
invoke the method not in given state)
ο InterruptedException
ο IllegalArgumentException
7decret.com 70
71. String length
ο String Length
int length( )
ο String Concatenation
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
7decret.com 71
75. equals( ) Versus ==
ο The equals( ) method compares the
characters inside a String object. The == operator
compares two object references to see whether they
refer to the same instance.
7decret.com 75
76. compareTo( )
ο A string is less than another if it comes before the
other in dictionary order.
ο int compareTo(String str)
7decret.com 76
77. Searching Strings
ο String class provides two methods
ο indexOf( ) Searches for the first occurrence of a
character or substring.
ο lastIndexOf( ) Searches for the last occurrence of a
character or substring.
7decret.com 77
78. Modifying a String
ο Because String objects are immutable:-
ο either copy it into a StringBuffer
ο use one of the following String methods
7decret.com 78
82. Reading Console Input
ο To obtain a character-based stream that is attached to the
console, you wrap System.in in a BufferedReader object, to
create a character stream. BuffereredReader supports a
buffered input stream.
ο Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters.
7decret.com 82
83. Reading Strings
ο To read a string from the keyboard, use the version of
readLine( ) that is a member of the
BufferedReader class. Its general form is shown
here:
ο String readLine( ) throws IOException
7decret.com 83
84. Writing Console Output
ο write( ) can be used to write to the console. The
simplest form of write( ) defined by PrintStream is
shown here:
ο void write(int byteval)
7decret.com 84
85. PrintWriter
ο PrintWriter is one of the character-based classes.
Using a character-based class for console output
makes it easier to internationalize your program
ο PrintWriter(OutputStream outputStream, boolean
flushOnNewline)
7decret.com 85
86. Reading and Writing Files
ο Two of the most often-used stream classes are
FileInputStream and FileOutputStream, which create byte
streams linked to files. To open a file, you simply create an
object of one of these classes, specifying the name of the file
as an argument to the constructor. While both classes
support additional, overridden constructors, the following
are the forms that we will be using
cont..
7decret.com 86
87. Reading and Writing Files
ο FileInputStream(String fileName) throws
FileNotFoundException
ο FileOutputStream(String fileName) throws
FileNotFoundException
ο To write to a file, you will use the write( ) method defined by
FileOutputStream.
ο Its simplest form is shown here:
ο void write(int byteval) throws IOException
7decret.com 87
88. Native Methods
ο you may want to call a subroutine that is written in a
language other than Java. Typically, such a subroutine
exists as executable code for the sCPU and
environment in which you are workingβthat
is, native code.
7decret.com 88
89. Window Fundamentals
ο The two most common windows are those derived
from Panel, which is used by applets, and those
derived from Frame
7decret.com 89
90. Component
ο Component is an abstract class that encapsulates all of the
attributes of a visual component. All user interface elements
that are displayed on the screen and that interact with the
user are subclasses of Component.
ο A Component object is responsible for remembering the
current foreground and background colors and the currently
selected text font.
7decret.com 90
92. Container
ο Component objects to be nested within it. Other
Container objects can be stored inside of a Container
(since they are themselves instances of Component).
This makes for a multileveled containment system. A
container is responsible for laying out (that is, positioning)
any components that it contains. It does this through the use
of various layout managers,
7decret.com 92
93. Panel
ο The Panel class is a concrete subclass of Container. It doesnβt
add any new methods; it simply implements container. A
Panel may be thought of as a recursively nestable,concrete
screen component.
ο a Panel is a window that does not contain a title bar, menu
bar, or border. This is why you donβt see these items when an
applet is run inside a browser
7decret.com 93
94. Panel
ο Components can be added to a Panel object by its add( )
method (inherited from Container). Once these components
have been added, you can position and resize them manually
using the setLocation( ), setSize( ), or setBounds( ) methods
defined by Component.
7decret.com 94
95. Window
ο The Window class creates a top-level window. A top-level
window is not contained within any other object; it sits
directly on the desktop. Generally, you wonβt create Window
objects directly. Instead, you will use a subclass of Window
called Frame
7decret.com 95
96. Frame
ο It is a subclass of Window and has a title bar, menu
bar, borders, and resizing corners.
7decret.com 96
97. Canvas
ο Canvas encapsulates a blank window upon which
you can draw.
ο it is not part of the hierarchy for applet or frame
windows
7decret.com 97
98. Working with Frame Windows
ο Frame( )
ο Frame(String title)
7decret.com 98
99. Setting the Windowβs
Dimensions
ο The setSize( ) method is used to set the dimensions of
the window. Its signature is shown here:
ο void setSize(int newWidth, int newHeight)
ο void setSize(Dimension newSize)
ο The getSize( ) method is used to obtain the current size
of a window. Its signature is shown here:
ο Dimension getSize( )
7decret.com 99
100. Hiding and Showing a Window
ο After a frame window has been created, it will not be
visible until you call
ο setVisible( ). Its signature is shown here:
ο void setVisible(boolean visibleFlag)
7decret.com 100
101. Setting a Windowβs Title
ο You can change the title in a frame window using
setTitle( ), which has this
ο general form:
ο void setTitle(String newTitle)
7decret.com 101
102. Closing a Frame Window
ο When using a frame window, your program must
remove that window from the screen when it is
closed, by calling setVisible(false). To intercept a
window-close event, you must implement the
windowClosing( ) method of the WindowListener
interface.
7decret.com 102
103. Setting the Paint Mode
ο The paint mode determines how objects are drawn in a
window. By default, new output to a window
overwrites any preexisting contents. However, it is
possible to have new objects XORed onto the window
by using setXORMode( ), as follows:
ο void setXORMode(Color xorColor)
7decret.com 103
104. Setting the Paint Modeβ¦.
ο To return to overwrite mode, call setPaintMode( ), shown
here:
ο void setPaintMode( )
ο In general, you will want to use overwrite mode for normal
output, and XOR mode for special purposes.
7decret.com 104
105. Creating and Selecting a Font
ο To select a new font, you must first construct a Font object
that describes that font.One Font constructor has this
general form:
ο Font(String fontName, int fontStyle, int pointSize)
ο The size, in points, of the font is specified by pointSize. To
use a font that you have created, you must select it using
setFont( ), which is defined by Component. It has this
general form:
ο void setFont(Font fontObj)
7decret.com 105
110. Using a TextField
ο TextField( )
ο TextField(int numChars)
ο TextField(String str)
ο TextField(String str, int numChars)
7decret.com 110
111. Using a TextArea
ο TextArea( )
ο TextArea(int numLines, int numChars)
ο TextArea(String str)
ο TextArea(String str, int numLines, int numChars)
ο TextArea(String str, int numLines, int numChars, int
sBars)
7decret.com 111
112. BorderLayout
ο The BorderLayout class implements a common layout
style for top-level windows. It has four narrow, fixed-width
components at the edges and one large area in the center.
ο The four sides are referred to as north, south, east, and west.
The middle area is called
ο the center. Here are the constructors defined by
BorderLayout:
7decret.com 112
113. GridLayout
ο GridLayout lays out components in a two-dimensional
grid. When you instantiate a GridLayout, you define the
number of rows and columns. The constructors
supported by GridLayout are shown here:
ο GridLayout( )
ο GridLayout(int numRows, int numColumns )
ο GridLayout(int numRows, int numColumns, int horz, int
vert)
7decret.com 113
114. CardLayout
ο The CardLayout class is unique among the other
layout managers in that it stores several different
layouts. Each layout can be thought of as being on a
separate index card in a deck that can be shuffled so
that any card is on top at a given time. This can be
useful for user interfaces with optional components
that can be dynamically enabled and disabled upon
user input.
7decret.com 114
115. CardLayout
ο You can prepare the other layouts and have them
hidden,ready to be activated when needed.
ο CardLayout provides these two constructors:
ο CardLayout( )
ο CardLayout(int horz, int vert)
7decret.com 115
116. Using a TextArea
ο TextArea( )
ο TextArea(int numLines, int numChars)
ο TextArea(String str)
ο TextArea(String str, int numLines, int numChars)
ο TextArea(String str, int numLines, int numChars, int
sBars)
7decret.com 116