Java Programming Concepts
CONTENTS
1. ARRAY STRING AND VECTORS 2. INTERFACES: MULTIPLE INHERITANCES
3. PACKAGES: PUTTING CLASSES 4. MULTITHREADED PROGRAMMING
TOGETHER
01
ARRAY STRING AND VECTORS
ARRAY
Array is a group of contiguous or related data items that share a common name. eg salary[10]. It has two types:
• One-dimensional array
• Two-dimensional array
One-dimensional array
A list of items can be given one variable name using only one
subscript and such a variable is called a single variable or a
one-dimensional array.
• Eg: numer[3], x[2]
Creating an array
An array must be declared and created in the computer
memory before they are used.
• Creation of array involves three steps:
• Declaring array
• Creating memory location
• Putting values into the memory location.
Declaration of array
It has two forms
• type array name[];
• type [] array name;
• eg: int number[], float[] marks
Creation of array
After declaring an array we need to create in the memory. Java
allows us to create an array using a new operator only.
• arrayname = new type[size]
• Eg: number = new int[5]
Initialization of array
The final step is to put values into the array created. This
process is known as initialization.
• arrayname[subscript] = value:
• Eg: number[0]=35; number[1]=40; ... number[4]=19
Array Length
We can obtain the length of the array a using a.length.
• Eg: intsSize = a.length
Example Class numberSorting
class numberSorting { public static void main (String args[]) { int number[] = {55, 40, 80, 65, 71};
int n = number.length; // array length. System.out.println("Given list:"); for(int i=0; i<n; i++) {
System.out.println("" + number[i]); } System.out.println("/n"); // sorting begins:
for(int i=0; i<n; i++) { for(int j=i+1; j<n; j++) { if(number[i] < number[j]) { //
interchange values int temp = number[i]; number[i] = number[j];
number[j] = temp; } } } // sorting end System.out.println("sorting list");
for(i=0; i<n; i++) { System.out.println("" + number[i]); } System.out.println(" "); }}
STRING
String represents a sequence of characters.
1 2 Strings are class objects and implemented
The easiest way to represent a sequence of
using two classes, namely, String and
characters in Java is by using a character
StringBuffer. A Java string is not a character
array.
array and is not NULL terminated. String may
• Eg: char charArray[] = new char[4];
be declared and created as follows:
• String stringName;
• stringName = new String ("String")
• Eg: String firstName; firstName = new
String("Anil");
String Methods
The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks.
Method Call Task performed
s2 = s1.toLowerCase() Converts the string s1 to all lowercase
s2 = s1.toUpperCase() Converts the string s1 to all Uppercase
s2 = s1.replace('x', 'y') Replace all appearances of x with y
s2 = s1.trim() Remove white spaces at the beginning and end of
the string s1
s1.equals(s2) Returns 'true' if s1 is equal to s2
Alphabetical ordering of strings
class StringOrdering { static String name[] = {"Madras", "Delhi", "Ahmedabad", "Calcutta", "Bombay"};
public static void main(String args[]) { for (int j = i + 1; j < size; j++) { if
(name[j].compareTo(name[i]) < 0) { // swap the strings String temp = name[i];
name[i] = name[j]; name[j] = temp; } } for (int i = 0; i < size; i++)
{ System.out.println(name[i]); } }}
Produces the following sorted list:
• Ahmedabad
• Bombay
• Calcutta
• Madras
StringBuffer Class
String Buffer is a peer class of String. While String creates
strings of fixed length, String Buffer creates strings of flexible
length that can be modified in terms of both length and
content. We can insert characters and substrings in the middle
of a string, or append another string to the end.
Commonly Used StringBuffer Methods
Method Task
s1.setCharAt(n, 'x') Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n, s2) Inserts the string s2 at the position n of the string
s1
s1.setLength(n) Sets the length of the string s1 to n. If n <
s1.length(), zeros are added to s1
String manipulations
class StringManipulation { public static void main(String args[]) { StringBuffer str = new
StringBuffer("Object Oriented"); System.out.println("Original String: " + str); // obtaining string
length System.out.println("Length of string: " + str.length()); // Accessing characters in a string
for (int i = 0; i < str.length(); i++) { int p = i + 1; System.out.println("Character at position: "
+ p + " is " + str.charAt(i)); } // Inserting a string in the middle String aString = new
String(str.toString()); int pos = aString.indexOf("Oriented"); str.insert(pos, "Object ");
System.out.println("Modified string: " + str); // Modifying characters str.setCharAt(6, '-');
System.out.println("String now: " + str); // Appending a string at the end str.append(" improves
security"); System.out.println("Append String: " + str); }}
VECTOR
The J2SE version supports the concept of variable arguments to methods. This feature can also be
achieved in Java through the use of the Vector class contained in the java.util package. This class can be
used to create a generic dynamic array known as vector that can hold objects of any type and any
number. The objects do not have to be homogeneous. Array can be easily implemented as vectors.
Creating Vectors
Vectors are created like arrays as follows:
• Vector intVect = new Vector(); // declaring without size
• Vector list = new Vector(3); // declaring with size
• Note that a vector can be declared without specifying any
size explicitly. A vector without size can accommodate an
unknown number of items.
Advantages of Vectors
1 It is convenient to use vectors to store objects.
2 A vector can be used to store a list of objects that may vary in size.
3 We can add and delete objects from the list as and when required.
Important Vector Methods
Method Task
list.addElement(item) Adds the item specified to the list at the end
list.elementAt(10) Gives the name of the 10th object
list.size() Gives the number of objects present
list.removeElement(item) Removes the specified item from the list
list.removeElementAt(n) Removes the item stored in the nth position of the
list
list.removeAllElements() Removes all the elements in the list
Working with Vectors and Arrays
import java.util.*; // Importing Vector class class
LanguageVector { public static void main(String
Command line input and output are:
args[]) { Vector list = new Vector(); int
length = args.length; for(int i = 0; i < length; • C: JAVAlprog> Java LanguageVector
i++) { list.addElement(args[i]); }
• List of Languages:
list.insertElementAt("COBOL", 2); int size =
list.size(); String listArray[] = new • Ada
String[size]; list.copyInto(listArray); • BASIC
System.out.println("List of Languages");
for(int i = 0; i < size; i++) • COBOL
{ System.out.println(listArray[i]); } • C++
}}
• FORTRAN
• Java
Wrapper Classes
Vectors cannot handle primitive data types like int, float, long, char, and double. Primitive data types
may be converted into object types by using the wrapper classes contained in the java.lang package.
Wrapper Classes for Converting Simple Types
Simple Type Wrapper Class
Boolean Boolean
Char Character
Double Double
Float Float
Int Integer
Long Long
Converting Primitive Numbers to Object
Numbers Using Constructor Methods
Constructor Calling Conversion Action
Integer intVal = new Integer(i); Primitive integer to Integer object
Float floatVal = new Float(f); Primitive float to Float object
Double doubleVal = new Double(d); Primitive double to Double object
Long longVal = new Long(l); Primitive long to Long object
Converting Object Numbers to Primitive
Numbers Using typeValue() method
Method Calling Conversion Action
int i = intVal.intValue(); Object to primitive integer
float f = floatVal.floatValue(); Object to primitive float
long l = longVal.longValue(); Object to primitive long
double d = doubleVal.doubleValue(); Object to primitive double
Converting Numbers to Strings Using
toString() Method
Method Calling Conversion Action
str = Integer.toString(i) Primitive integer to string
str = Float.toString(f) Primitive float to string
str = Double.toString(d) Primitive double to string
str = Long.toString(l) Primitive long to string
Converting String Objects to Numeric
Objects Using the Static Method ValueOf()
Method Calling Conversion Action
doubleVal = Double.valueOf(str); Converts string to Double object
floatVal = Float.valueOf(str); Converts string to Float object
intVal = Integer.valueOf(str); Converts string to Integer object
longVal = Long.valueOf(str); Converts string to Long object
Converting Numeric Strings to Primitive
Numbers Using Parsing Methods
Method Calling Conversion Action
int i = Integer.parseInt(str) Converts string into primitive integer
long i = Long.parseLong(str) Converts string into primitive Long
Enumerated Types
J2SE 5.0 allows us to use the enumerated type in Java using the enum keyword. This keyword can be
used similar to the static final constants in the earlier version of Java.
public class WorkingDays { enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday } public static void main(String args[]) { for (Days d : Days.values())
{ weekend(d); } } private static void weekend(Days d) { if(d.equals(Days.Sunday))
System.out.println("value=" + d + " is a holiday"); else System.out.println("value=" + d + "
is a working day"); }}
Annotations
The annotations feature, introduced by J2SE 5.0, is also known
as metadata. We can use this feature to merge additional Java
elements with the programming elements, such as classes,
methods, parameters, local variables, packages, and fields.
Standard Annotations
Annotation Purpose
@Deprecated Compiler warns when deprecated java elements
are used in non-deprecated program
@Override Compiler generates an error when the method
using this annotation type does not override the
methods present in the superclass.
Meta-annotations
Meta-annotation Purpose
@Documented Indicates annotation of this type to be
documented by Javadoc
@Inherited Indicates that this type is automatically inherited
@Retention Indicates the extended period using annotation
type
@Target Indicates to which program element the
annotation is applicable
Declaration of Annotation
package njunit.annotation; import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) public @interface UnitTest
{ String value(); }
Using Annotations
import java.lang.annotation.*; import java.lang.reflect.*; @Retention(RetentionPolicy.RUNTIME) @interface
MySingle { int value(); // this variable name must be value } public class Single { // Annotate a method
using a marker. @MySingle(100) public static void myMeth() { Single ob = new Single(); try {
Method m = ob.getClass().getMethod("myMeth"); MySingle anno =
m.getAnnotation(MySingle.class); System.out.println("The value is: " + anno.value()); // displays 100
} catch (NoSuchMethodException exc) { System.out.println("Method Not Found."); } }
public static void main(String args[]) { myMeth(); }}
The output of the above program is: The value is: 100
02
INTERFACES: MULTIPLE INHERITANCES
Introduction
We discussed classes and how they can be inherited by other
classes. We also learned about various forms of inheritance
and pointed out that Java does not support multiple
inheritance. That is, classes in Java cannot have more than one
superclass.
Defining Interfaces
An interface is basically a kind of class. Like classes, interfaces
contain methods and variables but with a major difference. The
difference is that interfaces define only abstract methods and
final fields. This means that interfaces do not specify any code
to implement these methods and data fields contain only
constants.
Syntax for Defining an Interface
interface InterfaceName { Variable declaration; Methods declaration; }
Here, interface is the keyword and InterfaceName is any valid Java variable (just like class names).
Variables are declared as follows:
static final type VariableName = value;
Example of an Interface
Definition
interface Item { static final int code = 1001; static final String
name = "Fan"; void display(); }
Extending Interfaces
Like classes, interfaces can also be extended. That is, an
interface can be sub-interface from other interfaces. The new
sub-interface will inherit all the members of the super interface
in the manner similar to subclasses.
Example of Combining Interfaces
interface ItemConstants { int code = 1001; String name = "Fan"; } interface ItemMethods { void
display(); } interface Item extends ItemConstants, ItemMethods { // methods here }
Implementing Interfaces
Interfaces are used as “superclasses” whose properties are inherited by classes. It is therefore necessary
to create a class that inherits the given interface.
class ClassName extends SuperClass implements Interface1, Interface2 { // body of ClassName }
Program Example
interface Area { final static float pi = 3.14F; float compute(float x, float y); } class Rectangle implements
Area { public float compute(float x, float y) { return (x * y); } } class Circle implements Area
{ public float compute(float x, float y) { return (pi * x * x); } } class InterfaceTest { public static
void main(String args[]) { Rectangle rect = new Rectangle(); Circle cir = new Circle(); Area
area; area = rect; System.out.println("Area of rectangle = " + area.compute(10, 20)); area =
cir; System.out.println("Area of Circle = " + area.compute(10, 0)); }}
The output is as follows:
• Area of Rectangle = 200
• Area of Circle = 314
Accessing Interface
Variables
Interfaces can be used to declare a set of constants that can
be used in different classes.
Program Example for Multiple Inheritance
class Student { int rollNumber; void getNumber(int n) { rollNumber = n; } void putNumber() {
System.out.println("Roll No: " + rollNumber); } } class Test extends Student { float part1, part2;
void getMarks(float m1, float m2) { part1 = m1; part2 = m2; } void putMarks()
{ System.out.println("Marks obtained"); System.out.println("Part 1 = " + part1);
System.out.println("Part 2 = " + part2); } } interface Sports { float sportsWt = 6.0F; void putWt(); }
class Results extends Test implements Sports { float total; public void putWt()
{ System.out.println("Sports wt = " + sportsWt); } void display() { total = part1 + part2 +
sportsWt; putNumber(); putMarks(); putWt(); System.out.println("Total score = " + total);
} } class Hybrid { public static void main(String args[]) { Results student1 = new Results();
student1.getNumber(1234); student1.getMarks(27.5F, 33.0F); student1.display(); }}
Output of the program is:
• Roll No: 1234
• Marks obtained
• Part 1 = 27.5
• Part 2 = 33
• Sports wt = 6.0
• Total score = 66.5
03
PACKAGES: PUTTING CLASSES TOGETHER
Definition of Packages
Packages are containers for classes that are used to keep the
class namespace compartmentalized. Packages are stored in a
hierarchical manner and are explicitly imported into a new
class definition.
Java Source File Parts
A Java source file may contain any one or all of the following
four internal parts:
• A single package statement
• Any number of import statements
• A single public class declaration
• Any number of classes private to the package
Defining a Package
To create a package, include the package command as the first
statement in your program followed by the package name.
package pkg;
Where pkg is the name of the package. Any classes inside the
file belong to the specified package.
Class Path
To make this work, you have two ways:
; c:\Myspace; c:\java\classes
• You can go one hierarchy up by one level and try it as java
Myspace.
• You can set the Classpath as:
Importing Packages
If you want to access a member of a class in a package, you need to specify the
packagename.classname. Sometimes if a class belongs to a multilevel hierarchical package you need to
type all the packages for every class you need to use. You can avoid this by using import statement.
Example of Importing
Packages
import Myspace.*; public class IntDemo { public static void
main(String args[]) { Interest i = new Interest(4, 500, 2);
i.calculate(); }}
04
MULTITHREADED PROGRAMMING
Introduction to
Multithreading
Those who are familiar with modern operating systems such as
Windows 95 and Windows XP may recognize that they can
execute several programs simultaneously, which is called
multitasking. In system terminology, this is known as
multithreading.
Creating Threads
Threads are implemented in the form of objects that contain a
method call run(). It is the heart and soul of any thread.
Starting a New Thread
A new thread can be created in two ways:
• By creating a thread class: define a class that extends the thread class and override its run() method
with the code required by the thread.
• By converting a class to a thread: Define a class that implements a runnable interface.
Extending the Thread Class
The class is runnable as a thread by extending the class
java.lang.Thread.
Program Example: Creating Threads
class A extends Thread { public void run() { for (int i = 1; i <= 5; i++) { System.out.println("t
From Thread A: i=" + i); } System.out.println("Exit from A"); } } class B extends Thread
{ public void run() { for (int j = 1; j <= 5; j++) { System.out.println("t From Thread B: j=" + j);
} System.out.println("Exit from B"); } } class C extends Thread { public void run() { for
(int k = 1; k <= 5; k++) { System.out.println("t From Thread C: k=" + k); }
System.out.println("Exit from C"); } } class ThreadTest { public static void main(String args[])
{ new A().start(); new B().start(); new C().start(); }}
Stopping and Blocking a
Thread
Stopping a thread
When we want to stop a thread, we call its stop() method.
Blocking a thread
A thread can be temporarily blocked from entering into the
runnable and subsequently running state by using either of the
following thread methods:
• sleep()
• suspend()
• wait()
Life Cycle of a Thread
New born state Runnable state Running state
Blocked state Dead state
Running State
The running state means that the processor has given its time to the thread for its execution.
Blocking State
A thread is said to be blocked when it is prevented from
entering into the runnable state and subsequently the running
state.
Dead State
A running thread ends its life when it has completed executing
its run() method.
Thread Methods
Thread class methods can be used to control the behavior of
the thread.
Program Example: Using Thread Methods
class A extends Thread { public void run() { for (int i = 1; i <= 5; i++) { if (i == 1) yield();
System.out.println("t From thread A: i=" + i); } System.out.println("Exit from A"); } } class B
extends Thread { public void run() { for (int j = 1; j <= 5; j++) { System.out.println("t From
thread B: j=" + j); if (j == 3) stop(); } System.out.println("Exit from B"); } } class C
extends Thread { public void run() { for (int k = 1; k <= 5; k++) { System.out.println("t From
thread C: k=" + k); if (k == 1) { try { sleep(1000); } catch
(Exception e) {} } } System.out.println("Exit from C"); } } class ThreadMethods
{ public static void main(String args[]) { A threadA = new A(); B threadB = new B(); C
threadC = new C(); System.out.println("Start thread A"); threadA.start();
System.out.println("Start thread B"); threadB.start(); System.out.println("Start thread C");
threadC.start(); }}
Thread Exception Handling
The call to sleep() method is enclosed in a try block and
followed by a catch block. This is necessary because the
sleep() method throws an exception.
Thread Priority
In Java, each thread is assigned a priority, which affects the
order in which it is scheduled for running. The threads of the
same priority are given equal treatment by the Java scheduler.
Using Priority Threads
class A extends Thread { public void run() { for (int i = 1; i <= 5; i++) { System.out.println("t
From thread A: i=" + i); } System.out.println("Exit from A"); } } class B extends Thread
{ public void run() { for (int j = 1; j <= 4; j++) { System.out.println("t From thread B: j=" + j);
} System.out.println("Exit from B"); } } class C extends Thread { public void run() { for
(int k = 1; k <= 4; k++) { System.out.println("t From thread C: k=" + k); }
System.out.println("Exit from C"); } } class ThreadPriority { public static void main(String args[])
{ A threadA = new A(); B threadB = new B(); C threadC = new C();
threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(ThreadA.getPriority() + 1);
threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Start thread A"); threadA.start();
System.out.println("Start thread B"); threadB.start(); System.out.println("Start thread C");
threadC.start(); System.out.println("End of the main thread"); }}
Synchronization
Java enables us to overcome the problem of multiple threads competing for the same resource using a
technique known as synchronization.
Implementing the Runnable Interface
It’s one way of creating the thread. That is implementing the runnable interface.
class X implements Runnable { public void run() { for (int i = 1; i <= 10; i++)
{ System.out.println("t Thread X: " + i); } System.out.println("End of Thread X"); }}
class RunnableTest { public static void main(String args[]) { X runnable = new X(); Thread thread
= new Thread(runnable); thread.start(); }}
Points to be Remembered
1 Sometimes class name conflict may occur. For 2 While creating a package, the package
example: statement should be the first statement of the
program, followed by the import statement.
• There are two packages myPackage1 and
myPackage2. Both of these packages contain
a class with the same name.
3 To create a package for a type, put a package 4 The path names for a package's source and
statement as the first statement in the source class files mirror the name of the package.
file that contains the type.
Suggested Questions
Section A Section B Section C
• What is an array? • What are the methods in the • Write notes on interfaces.
string class?
• How does Java handle strings? • How can access a package?
• Explain multiple inheritance.
• How to use strings and • Explain the life cycle of a
StringBuffer? • Explain packages with a thread.
program.
• What is a vector in Java? • Write notes on thread priority.
• Discuss about multithreading.
• How are wrapper classes
useful? • Describe one and two-
dimensional arrays.
Thank You