Professional Documents
Culture Documents
PREREQUISITES : Programming experience in at least one procedural language. Preferably C, C++. TARGET AUDIENCE : ELTP Trainees METHODOLOGY : Usage of slides Exercises to be solved in Lab Assignments and Quizzes
COURSE CONTENTS
Unit 1 : Object-oriented programming concepts Object Oriented Paradigm Classes, Objects, variables & methods Abstraction, encapsulation, inheritance, polymorphism Interfaces Unit 2 : Fundamental concepts of Java programming language History & characteristics of java. Primitive data types and objects Variables (Instance and Class) Arrays and Strings Control Structures Methods (Instance and Class) Packages & Interfaces A small sample application program
COURSE CONTENTS
Unit 3 : Exception handling Concept of Exception Handling Exception Types Uncaught Exceptions Claiming, Throwing and Handling Exceptions (using try-catch blocks) Using the finally clause in the try-catch block Creating User Exception Unit 4 : Multithreading Concept of Multithreading Writing threads by extending the Thread Class Writing threads by implementing the Runnable interface Life cycle of thread states Thread priorities and thread groups Thread synchronization and resource conflicts
COURSE CONTENTS
Unit 5 : Collections Maps Sets Trees Vectors Lists Iterators & Enumerations Hash Tables, Hash Maps. Unit 6 : IOs Streams InputStreams OutputStream Object Streams File Streams Pipe Streams Buffered Streams File Locking (nio package)
COURSE CONTENTS
Unit 7 : Util Package String Tokenize Date Calendar Introduction to java.util.jar & java.util.zip packages. Unit 8 : Other Important Concepts Compiler Options. javadoc tool. Security Over view.
COURSE CONTENTS
Unit 9 : IDE Introduction to IDE. Using Templates. Creating Classes, Interfaces, Packages from IDE. Compiling & running a java program from the IDE. Debugging Techniques. Debugging Java Programs from IDE. Unit 10 : AWT & Applet AWT Component, Container, Panel, Window, Frame, Canvas AWT Controls Menus Events Listeners Adapter classes
COURSE CONTENTS
Day Wise
Day Session 1 S1 S2 S3 S4 S1 S2 S3 S4 Topic Object-oriented programming concepts Fundamental concepts of Java programming language Writing application programs using Java Lab Session Executing a simple Java Program Exception handling Lab Session Exercises on Exception handling Multithreading Lab Session Exercises on Multithreading
COURSE CONTENTS
Day Wise
Day Session 3 S1 S2 S3 S4 S1 S2 S3 S4 Topic Java Collections Lab Session Exercises on Java Collection Java IOs Lab Session Exercises on Java IOs Security Overview Javadoc utility, Introduction IDE & debugging techniques Lab Session Exercises on Code Debugging Lab Session Exercises on Code Debugging
COURSE CONTENTS
Day Wise
Day Session 5 S1 S2 S3 S4 S5 S1 S2 S3 S4 Topic Introduction to AWT & Component Hierarchy) Frames Lab Session Exercises on Frames Events & Listeners Lab Session Exercises on java.awt.event Package Menus Lab Session Exercises on Menus Applets & Applet communications Lab Session Exercises on Applets
Java 2 Platform
J2EE
JDBC HTML, XML
Browser
HTTP Servlet or JSP RMI /IIOP Security Transactions Concurrency
Data
HOME REMOTE
Entity Bean
Device
any http server Session Bean
JDBC
Containers
JVM
Context
EJB Server
any OS
The Platform
Cache / Proxy / Fwall Commerce
Tools
Management
Tools
Integration Collaboration Content Mgmt J2EE Wireless/Mobile Data Application Server J2EE
Management
Java is
Similar in syntax to C++; similar in semantics to Smalltalk Used for developing both applets and applications
Enable users to run more than one thread of activity Support dynamically changing programs during runtime Furnish better security
Provides hardware platform specifications Reads compiled byte codes which are platform independent Is implemented as software Is implemented in a Java technology development tool or a Web browser
Instruction set (central processing until [CPU]) Class file format Stack Garbage-collection Memory area
Bytecodes that maintain proper type discipline form the code The majority of type checking is done when the code is compiled Every SunTM approved implementation of the JVM must be able to run any compliant class file.
Garbage Collection
Allocated memory that is no longer needed should be deallocated In other languages, deallocation is the programmers responsibility Garbage collection
Checks for and frees memory no longer needed Is done automatically Can vary dramatically across JVM implementations
Performs three main tasks Loads code Verifies code Executes code
Interpreter Runtime
Hardware
An Object
Everything is an object: If you want to model it and use it in your program.
Account 3
Account 1
Identity
ME
My Twin
Parts of an Object
Properties State Methods Constructors Access
Rights Destructor
Account 1
Black Listed
Account 1
Closed
Constructor
Tape Recorder
A and B are equal. B and C are similar C and D are neither similar nor equal. If they are equal they are the same object
Inheritance - is a
Account IS A Savings Account Current Account
Savings Account will have everything from account, as does the Current Account
Aggregation - has a
Engine HAS A
Car
Polymorphism
Is
a consequence of virtual functions Function to be called is decided at run time based on object This makes a function call behave differently with different objects
Abstract Class
Four Legged Animal
Cat
Rat
Interface
Radio Radio
Radio Tape
Comments
Block statements can be nested Any amount of whitespace is allowed in a Java program
Identifiers
Are names given to a variable, class or method Can start with a letter, underscore(_), or dollar sign($) Are case sensitive and have no maximum length
Primitive Types
The Java programming language defines eight primitive types Logical boolean Textual char Integer byte, short, int and long Floating double and float
Logical - boolean
The boolean data type has two literals, true and false For example the statement
boolean truth = true ;
declares the variable truth as boolean type and assigns it a value of true.
A tab A specific Unicode character (????) is replaced with exactly four hexadecimal digits.
Uses three forms - decimal, octal or hexadecimal 2 The decimal value is two. 077 The leading zero indicates an octal value 0xBAAC The leading 0x indicates a hexadecimal value Has a default int Defines long, by using the letter L or l
Default is double Floating point literal includes either a decimal point or one of the following E or e (add exponential value) F or f (float) D or d (double)
3.14 6.02E23 2.718F 123.4E+306D A simple floating-point value (a double) A large floating-point value A simple float size value A large double value with redundant D
Floating point data types have the following ranges: ------------------------------------------Float length 32 bits 64 bits
------------------------------------------float double
Name or Type
-------------------------------------------
Classes
class AccountBook class ComplexVariable
Interfaces
interface Account
Methods
balanceAccount () addComplex ()
Variables
currentCustomer
Constants
HEAD_COUNT MAXIMUM_SIZE
Understanding Objects
Declaring a variable
Date myBirth, yourBirth
Accessing members
myBirth.day = 26; myBirth.month = 11; yourBirth.year = 1960;
Creating an Object
Declaration of primitive types allocates memory space Declaration of nonprimitive types does not allocate memory space Declared variables are not the data itself, but references (or pointers) to the data
today
????
S T
Logical Expressions
The operators are && (AND) and ||(OR) Operators can be used as follows:
String unset = null; if ((unset != null) && (unset.length() > 5)) { // do something with unset }
The + operator Performs String concatenation Produces a new String For example:
String salutation = Dr.; String name = Pete + Seymour; String title = salutation + name;
One argument must be a String object Non-strings are converted to String objects automatically
The sign bit is copied during the shift. Logical or unsigned right shift operator (>>>) is Used for bit patterns Not copied during the shift
The equals () and = = methods determine if reference values refer to the same object. The equals () method is overridden in classes in order to return true if the contents and type of two separate objects match.
Casting
If information is lost in an assignment the programmer must confirm the assignment with a typecast. The assignment between short and char requires an explicit cast.
long bigValue = 99L; int squashed = (int) (bigValue); long bigval = 6;// 6 is an int type, OK int smallval = 99L;// 99L is a long, illegal float z = 12.414F;// 12.414F is Float, OK float zl = 12.414;// 12.414 is double, illegal
Variables are automatically promoted to a longer form (such as int to long) Expression is assignment compatible if the variable type is at least as large (the same number of bits) as the expression type.
Branching Statements
The if, else statements if (boolean expression) { statement or block; } if (condition is true) { statement or block; } else { statement or block; }
Branching Statements
The switch Statement
The switch statement syntax is: switch (expr1) { case expr2: statements; break; case expr3: statements; break; default: statements; break; }
Looping Statements
The for statement for (init_expr; boolean testexpr; alter_expr) { statement or block; }
Looping Statements
The While loop while (boolean) { statement or block; }
Looping Statements
The do/while statement do { statement or block; } while (boolean test)
break [label] ; continue [label]; label: statement;//where statement must be any // legal statement
Declaring Arrays
Group data objects of the same type Declare arrays of primitive or class types
char s[]; Point p[]; char [] s; Point [] p;
Create space for a reference Remember an array is an object not memory reserved for primitive types
Creating Arrays
Use the new keyword to create an array object
s = new char [20]; p = new point [100]; p[0] = new point(); p[1] = new point(); . . .
Example : ArrayDemo.java
Initializing Arrays
An
Example : ArrayOfStringDemo.java
Multi-Dimensional Arrays
Arrays of arrays int twoDim [][] = new int [4][] ; twoDim [0] = new int[5]; twoDim [1] = new int[5]; int twoDim [][] = new int [][4]; illegal Array of four arrays of five integers each int twoDim [][] = new int[4][5];
Multi-Dimensional Arrays
Array Bounds
All array subscripts begin at 0
int list [] = new int [10]; for (int i = 0; i < list.length; i++) system.out.println(list[i]);
Copying Arrays
Cannot resize an array Can use the same reference variable to refer to an entirely new array
int elements [] = new int[6]; elements = new int[10];
Copying Arrays
The System.arraycopy () method
//original array int elements[] = { 1,2,3,4,5,6 }; : //new larger array int hold[] = { 10,9,8,7,6,5,4,3,2,1 }; //copy all of the elements array to the hold //array, starting with the 0th index System.arraycopy (elements, 0, hold, 0, elements.length);
Strings
Strings are objects that are immutable Using Strings : String name=Rajesh; String name = new String(Rajesh); String fullname = name + Kumar; name = name + Kumar; Important methods of string class : charAt(), substring(), length(), toUpperCase(), toLowerCase(), trim(), valueOf()
Constructors
Method used to initialize an object Method name same as the class name Java provides the default constructor for a class We can have overloaded constructors class Employee { int no; String name; Employee() { no=100; name=Rajesh; } }
Is shared among all instances of a class Can be marked either as public or as private Can be accessed from outside the class if marked as public without an instance of the class.
public class Count { private int serialNumber; private static int counter = 0; public Count () { counter++; serialNumber = counter; } }
A final class cannot be subclassed A final method cannot be overridden A final variable is a constant
Abstract Classes
A class which declares the existence of methods but not the implementation is called an abstract class. A class can be declared as abstract by marking it with the abstract keyword.
public abstract class Drawing { public abstract void drawDot {int x, int y); public void drawLine (int x1, int y1, int x2, int y2) { // draw using the drawDot () method repeatedly. } }
Interfaces
An interface is a variation on the idea of an abstract class. In an interface, all the methods are abstract. Multiple inheritance can be achieved by implementing such interfaces The syntax is
public interface Transparency { public static final int OPAQUE = 1; public static final int BITMASK = 2; public static final int TRANSLUCENT = 3; public int getTransparency(); }
Interfaces
Interfaces are useful for Declaring methods that one or more classes are expected to implement Determining an objects programming interface without revealing the actual body of the class Capturing similarities between unrelated classes without forcing a class relationship Describing function-like objects that can be passed as parameters to methods invoked on other objects
String
Constructors : String(
char[]) String(char[], int Start, int No) String(byte[]) String(byte[], int Start, int No) String(String)
Methods : Length(
) - Returns the number of characters charAt(int) - Returns char at the given index getChars(int St, int End, char[] Dest, int StDes) toCharArray( ) - Returns character array getBytes(int St, int End, byte[] Dest, int StDes) equals(String) - Compares two Strings,returns
boolean.
equalsIgnoreCase(
Methods : compareTo(
) - Returns integer startsWith(String) - Returns boolean,case sensitive endsWith(String)- Returns boolean,case sensitive trim( ) - Removes blank spaces on either sides replace(char Old, char New) - For replacing Old
chars
concat(String)
- Creates a new String by adding subString(int) - Creates a String from int to the end
Cont...
- Returns int,index of first occurence lastIndexOf(char) - Returns int,index of last occurence indexOf(String) - Returns int,index of first occurence lastIndexOf(String)- Returns int,index of last
occurence
Stringbuffer
Constructors : Stringbuffer(
) - 16 bytes of buffer by default String buffer(int) - For specifying the size String buffer(String) - For specifying the size
Methods : Length(
) - Returns the number of characters capacity( ) - Returns capacity setLength (int len) - Sets the new length charAt(int) - Returns character at the index getChars(int St, int End, char[] Dest, int StDes)
Cont...
Methods : setCharAt(int,
char) - Sets the char at the int append(String)-Adds the string to the current string insert(int, String) - Inserts the string at the index toString( ) - Returns string reverse( ) - Reverses the string
Points to Note
Use
StringBuffer wear the string values constantly change. Because a new string object is created for every change of value for a String class.
Lab Session
Q. which of the following variable names are invalid, and why? Minimum double float First.name 3rd_row Sum Total n1+ n2 &name n$ Row1 Row Total Column-total
Q. Shown below is a Floyds triangle. 1 2 3 4 5 6 .. 79 91 Write a program to print this triangle? (FloydTriangle.java)
Solution
class FloydTriangle { public static void main(String []args) { int j; for(int i=1;i<6;i++) { for(j=1;j<=i;j++) System.out.print(j+"\t"); System.out.print("\n\n"); } } }
Lab Session
Write the segment of the program that creates the array as follows. 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
Solution
Example : FloydTriangle.java
Lab Session
The annual examination results of 5 students are tabulated as follows. write the main method in order to determine the following a) Find out the total marks obtained by each student. b) The highest marks in each subject and roll no of the student who secured it. Use the following class to create the objects class Student{ int rollNo; String name; int sub1, sub2,sub3; }
Lab Session
Consider a college running 4 departments (MPC, BPC, HEC, CEC) the subject of each of the departments is given below. CEC MPC Lang 1 Lang 1 Lang 2 Lang 2 Commerce Mathematics Economics Physics Civics Chemistry BPC Lang 1 Lang 2 Biology Physics Chemistry HEC Lang 1 Lang 2 History Economics Civics
Solution
Marks
Arts Marks
Science Marks
HEC Marks
CEC Marks
MPC Marks
BPC Marks
Abstract Classes HEC Marks CEC Marks MPC Marks BPC Marks
Final Classes
Objective: This is a story based exercise. The exercise enables the participants to pause at different stages and review the work they had done and the changes that need to be carried out to meet new requirements, that crop up from time to time. The Objective is to develop an object oriented system, using Java. The participant is expected to visualize various approaches to solve a problem, evaluate the approaches and develop a solution using the best option. The participant is required to refer to the Java language specifications to study the facilities offered by the Java API.
Exercise (contd..)
Note:
The participant is required to look into the best practices of Java (PPT version), while doing the exercise.
Exercise (contd..)
1.
A student joins the Satyam University. He sits at the workspace allotted to him. He runs the Hello.java program by keying in java Hello and he sees the welcome message 2. However, he wishes to be welcomed by name. He modifies the program. 3. experiments by overloading the main method.
Exercise (contd..)
4.
In the next program [4], the student enters the marks he has scored in 5 subjects and the program outputs the average marks. Grading on a scale of A to D is done with the following range of values for the grade.
Exercise 4 (contd)
Grade A B C D Average marks > 80 % >= 70 and < 80% >= 60 and < 70% < 60%
Exercise (contd..)
5.
Before grading the students, the program checks whether the student is above a minimum age which is stipulated in another class. 6. The other class has facilities to set and get the minimum age. The other class should reside in a package called stipulations
MPC BPC
HEC CEC
Maths, Physics, Chemistry, lang1, lang2 Biology, Physics, Chemistry, lang1, lang2
History, Economics, Civics, lang1, lang2 Commerce, Economics, Civics, lang1, lang2
A student belongs to one of the 4 types of students viz. MPCStudent/BPCStudent/HECStudent/CECStudent. Hence, a student object belonging to a particular class should have its class implement the corresponding MarksInterface
Exercise (contd..)
8. SU gets the input data for students in the below format: #StudentNumber;StudentFirstName; StudentFirstName subjectName=Marks;.. For the current exercise, the input data is treated as held in the form of a String object, rather than getting it from a file. The data has to be extracted from the String object, the student objects have to be created and stored in an array of Student objects. Initially, the extracted data is to be printed onto the console
Exercise (contd..)
9. 10.
And then stored into the array of Student objects The next requirement is that the first and last names should be concatenated and displayed. One of the developers suggests that a StringBuffer class could be used. Weigh the pros and cons of using the StringBuffer and write a new class for carrying out the concatenation.
The
remainder part of the story exercises will be continued in the next session. ThankQ