IAC 2024 - IA Fast Track to Search Focused AI Solutions
Shiksharth com java_topics
1. CORE JAVA
DEMO SESSION
Rajesh Verma
SHIKSHARTH.COM
(an education venture of Sunvision Software Technologies)
Objective : to give trial session on Java to students (for JCP program)
Copyrights, Sunvision Software Technologies
2. Demo Session - Outline
● What is JAVA?
● Do you know C/C++?
● Do you know JAVA?
● Difference between Java & C/C++
● Lets write first Java program
● What you require
● Make your machine Java Ready
● Open a text file “HelloSHIKSHARTH.java”
● Compile
● Run
● Knowledge sharing on a topic (USP)
● What you will learn : course outline
● Why Java? (discuss job opportunities)
● Share few applications or portals
● Talk to me on Java
3. Introduction to Java :
HelloJava.java (simplest program)
1. Write Program : vi HelloJava.java or in Notepad
class HelloJava
{
public static void main(String args[])
{
System.out.prinln(“Hello Java!!”);
}
}
2. Compile : javac HelloJava.java (generates HelloJava.class)
3. Run : java HelloJava (without extension)
4. CORE JAVA Rajesh Verma
SHIKSHARTH.COM
(an education venture of Sunvision Software Technologies)
Objective : to cover programing aspect rather theoretical coverage
Copyrights, Sunvision Software Technologies
5. Core Java : Course Snapshot
● Chapter 1 : Introduction to Java 2 Days
➢ OOPS Concept
➢ Arrays and String
➢ Package
➢ Class and Object
➢ Exception Handling
● Chapter 2 : I/O 1 day
➢ File Handling
➢ Networking
● Chapter 3 : Collection 1 day
➢ Hashtable
➢ Arraylist
➢ Map
● Chapter 4 : Database Connectivity 1 day
● Open discussion and market trend last day
6. Introduction to Java
● Programing standards
● Advantage over C/C++
● Features of Java
● Java development environment
● JVM architecture
● Introduction to class and object with sample
program
● Language Fundamental
7. Introduction to Java : Programing
Standards
●Corporate expectation from a good developer
➢ Paper work before writing any program
➢ Proper programing comments
➢ Program alignment
➢ Variable naming convention
➢ Readability and Maintainability of program
➢ Use of package & function for modularity
➢ Optimization and low memory consumption
➢ Performance, robustness and error handling
8. Introduction to Java : Advantage
• Java advantage
➢ Similar to C++
➢ Platform independent
➢ Can write mission critical application
• Over C/C++
➢ Excluding primitive data-types everything is object in Java
➢ Relief from C pointers
➢ Writing a bug-free code is easier in Java
➢ Automatic memory management using garbage collector
10. Introduction to Java : Development
● Java development environment
➢ Java SDK : jdk 1.6.x
➢ Java is installed in <mydir>/jdk1.6.x
➢ $JAVA_HOME = <mydir>/jdk1.6.x
➢ export PATH=$PATH:$JAVA_HOME/bin
➢ Check version : java -version
➢ export CLASSPATH=$CLASSPATH:....
➢ Compile command : javac myprg.java -classpath <...> -d <trg
dir>
➢ Run command : java myprg -classpath <...>
➢ Main class name and physical file should be same
➢ public static void main(String[] args) in main method
➢ Redirect output : java myprg > myoutput.txt
11. Introduction to Java :
HelloJava.java (simplest program)
1. Write Program : vi HelloJava.java or in Notepad
class HelloJava
{
public static void main(String args[])
{
System.out.prinln(“Hello Java!!”);
}
}
2. Compile : javac HelloJava.java (generates HelloJava.class)
3. Run : java HelloJava (without extension)
12. Introduction to Java : JVM
Java source code
● JVM architecture
➢ It acts like mini OS. Java byte code
➢ An abstract
computer on which Class loader
all Java programs
Byte code verification
run.
Execution engine
(JIT, Adaptive Optimizer)
Machine code
13. Introduction to Java : Class &
object
● A class is a blueprint or prototype that defines the variables and
methods common to all objects of a certain kind.
● Object itself is called as instance, these variables and methods are
called as instance variables and instance methods.
methods
● An Instance
– An instance of a class is created using “new” operator.
e.g. ClassName lClassName = new ClassName();
“new” operator allocate the required memory for instance.
– Accessor (get) methods : Access instance field values.
– Mutator (set, add) methods : change instance field values.
14. Introduction to Java : Example of
Class & object
class date
Instance 1 {
private int dd;
DOB private int mm;
private int yy;
void set_dd( int d ){dd =d;}
dd mm yy void set_mm( int d ){mm =m;}
void set_yy( int d ){yy =y;}
Instance 4 Instance 2
DOComp Set & get DOJoin int get_dd(){return dd;}
methods int get_mm(){return mm;}
int get_yy(){return yy;}
}
date => birth_day, marriage_day, ...
Instance 3
DO Exp
15. Introduction to Java : Language
Fundamental
● Language Fundamental
➢ Variables and constant identifiers
➢ Operators and assignment
➢ Flow control
16. Introduction to Java : Language
Fundamental : Variable & Constant
●variable-type var-name;
●final constant-name;
System.out.println
●Type casting
("lVarInteger : "+lVarInteger);
System.out.println
("lVarLong : "+lVarLong);
public class VariableNConstant System.out.println
{ ("lVarFloat : "+lVarFloat);
public static void main(String[] args) System.out.println
{ ("lVarDouble : "+lVarDouble);
int lVarInteger = 0; System.out.println
long lVarLong = 0; ("lVarChar : "+lVarChar);
float lVarFloat = (float)0.00; System.out.println
double lVarDouble = (double)0.00; ("lVarBoolean : "+lVarBoolean);
char lVarChar = 'Y'; System.out.println
boolean lVarBoolean = true; ("PIE_VALUE : "+PIE_VALUE);
final float PIE_VALUE = (float)3.14; }
}
17. Introduction to Java : Language
Fundamental : Variable & Constant
Compilation without type casting
found : double OUTPUT
required: float lVarInteger : 0
float lVarFloat = 0.00;
^
lVarLong : 0
VariableNConstant.java:16: lVarFloat : 0.0
possible loss of precision
found : double
lVarDouble : 0.0
required: float lVarChar : Y
final float PIE_VALUE = 3.14; lVarBoolean : true
^
2 errors PIE_VALUE : 3.14
18. Introduction to Java : Language
Fundamental : Primitive Data types
● 8 primitive data types are defined in Java.
● 4 Integer types
➢ byte memory space 1byte (+27 to -27)
➢
short memory space 2byte (+215 to -215)
➢
int memory space 4byte (+231 to -231)
➢
long memory space 8byte (+263 to -263)
● 2 Floating type
➢ float memory space 4byte (~6-7 decimals)
➢ double memory space 8byte (~15 decimals)
● 1 character type
➢ char memory space 2byte (due to Unicode)
● 1 boolean type
➢ boolean memory space 1byte
● Range formula : -2(bits-1) to +2(bits-1)-1
19. Introduction to Java : Language
Fundamental : Number Format
import java.text.*;
public class NumberFormat { System.out.println("---------------------");
df = new DecimalFormat("0.00000");
public static void main(String[] args) { System.out.println("lVarDouble (5 decimals) : "
float lVarFloat = (float)12.345678; +(df.format(lVarDouble)));
double lVarDouble df = new DecimalFormat("0.000000");
= (double)999.987654321; System.out.println("lVarDouble (6 decimals) : "
System.out.println +(df.format(lVarDouble))); } }
("lVarFloat : "+lVarFloat);
System.out.println
("lVarDouble : "+lVarDouble);
System.out.println("---------------------"); lVarFloat : 12.345678
DecimalFormat df = lVarDouble : 999.987654321
new DecimalFormat("0.000"); --------------------------
System.out.println("lVarFloat (3 decimals) :" lVarFloat (3 decimals) : 12.346
+(df.format(lVarFloat))); lVarFloat (4 decimals) : 12.3457
df = new DecimalFormat("0.0000"); --------------------------
System.out.println("lVarFloat (4 decimals):" lVarDouble (5 decimals) : 999.98765
+(df.format(lVarFloat))); lVarDouble (6 decimals) : 999.987654
25. OOPS Concept : Inheritance
● Process by which one object acquires the property of another
object.
● The class from which the properties are inherited is called Super
Class.
● The class which inherit the properties is called Sub Class.
● e.g. class B extends A{ }
A is super class and B is sub class.
● Final keyword
A final class can't be extended ie., final class may not be
subclassed. A final method can't be overridden when its class is
inherited. Final variable can't be changed its a constant.
26. OOPS Concept : Inheritance
class A{
public class BinA{ int i,j = 1;
public static void main(String args[]) void showij(){
{ System.out.println
A lA = new A(); ("i&j : " +i +” ”+j);
B lB = new B();
lA.showij();
}
lB.showk(); }
lB.sum(); class B extends A{
} int k = 2;
} void showk(){
System.out.println("k : " +k);
}
void sum(){
OUTPUT System.out.println
i&j : 0 1 ("i+J+k : " +(i+j+k));
k:2 }
i+J+k : 3 }
27. OOPS Concept : Abstraction
● Abstraction : generalized form (dictionary meaning).
● A class is defined as ABSATRACT using abstract keyword.
● This abstract class must have at-least one abstract method, i.e. Just a signature of method no function
body part.
● Subclasses must override all the methods of an abstract class.
● Syntax : abstract class class_name
{ ... abstract DATATYPE function_name(); .....}
● There can be no object of an abstract class i.e. An abstract class cannot be directly instantiated with a
new operator.
● Also we cannot declare an abstract constructor.
● A subclass extended by abstract class
● We can leave all abstract method undefined, (must be tagged as “abstract”) [OR]
● Define all methods (then subclass is not abstract)
● Object variable of abstract can only be created referring to non-abstract class e.g. Person p = new
Employee( .......... );
● Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is
abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static
data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
● A class may be declared abstract even if it has no abstract methods. This prevents it from being
instantiated.
28. OOPS Concept : Abstraction
class Employee extends Person {
public class PersonTest { public Employee(String n, double s) {
public static void main(String[] args) { // NAME | SALARY
Person[] people = new Person[2]; // pass name to superclass constructor
people[0] = new Employee super(n);
("Harry Hacker", 50000); salary = s; }
people[1] = new Student public double getSalary() { return salary; }
("Maria Morris", "computer science"); public String getDescription()
for (int i = 0; i < people.length; i++) { { return "salary " + salary; }
Person p = people[i]; private double salary;
System.out.println(p.getName() + ", " }//______________________
+ p.getDescription()); class Student extends Person {
} } }//_______________________ public Student(String n, String b) {
abstract class Person { // NAME | BRANCH
public Person(String n) { name = n; } // pass b to superclass constructor
public abstract String getDescription(); super(n);
public String getName() { return name; } branch = b; }
private String name; public String getDescription() {
} return "student branch " + branch; }
private String branch; }
Harry Hacker, salary 50000.0
Maria Morris, student branch computer science
29. OOPS Concept : Encapsulation
● Data hiding | Data binding
● Mechanism that binds code and data together, keeps both safe from outside
interference and misuse.
● 4 diff. access modifiers to access these types of methods & variables.
➢ auto : default modifier, available in sub-class.
➢ private : accessible within the class only
➢ public : accessible in all sub-classes
➢ protected : accessible only inside package. If inherited outside package all
protected members become private for that class.
● In Example, name field can't be accessed directly
30. OOPS Concept : Encapsulation
● public : Public class is visible in other packages, field is visible everywhere
(class must be public too)
● private : Private variables or methods may be used only by an instance of the
same class that declares the variable or method, A private feature may only be
accessed by the class that owns the feature.
● protected : Is available to all classes in the same package and also available to
all subclasses of the class that owns the protected feature.This access is
provided even to subclasses that reside in a different package from the class
that owns the protected feature.
● default :What you get by default ie, without any access modifier (ie, public
private or protected).It means that it is visible to all within a particular package.
31. OOPS Concept : STATIC
● static : Static means one per class, not one for each object no matter how many instance of a class might exist.
This means that you can use them without creating an instance of a class. Static methods are implicitly final,
because overriding is done based on the type of the object, and static methods are attached to a class, not an
object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the
original method was not declared final. However, you can't override a static method with a nonstatic method. In
other words, you can't change a static method into an instance method in a subclass.
● Figure 01 illustrates how to create a basic static class. Simply put the keyword static in the declaration of the
methods in the class. The declaration of the class itself requires no special decoration. The class can contain
static and non-static methods and properties simultaneously.
● Figure 02 contains a main() that references the static class. Note that the reference uses the class name, not an
object (instance) name. An instance is not required. An instance can reference a static member, but be sure to
have a thorough understanding of the side effects.
● Let's modify the static class. In Figure 03, the class has a new property, alpha, and a new method, SetAlpha().
SetAlpha() is public and alpha is private.
The SetAlpha() method references the private property alpha. Note that alpha and SetAlpha() are not declared as
static. All is well in the main(); it still builds and executes properly. No changes are necessary.
● In Figure 05 the main() is broken because it's illegal to reference a non-static method using a class reference. The
converse is permissible, but that's not the point of this exercise.
● OK, let's try to fix the error by declaring the SetAlpha( ) method static. Figure 05 illustrates the attempt.
● That fails. The SetAlpha( ) method cannot be declared static because it references a non-static variable, alpha.
Figure 06 illustrates the only way to fix the problem. The declaration of alpha must be modified to include the
keyword static. However, although the project now builds properly, we have created a situation in which only
one instance of the variable alpha will be created when the program runs.
● Static classes are commonly used to create classes that do not need to be instantiated and will be shared as a
single copy throughout the entire project. The static class is also a first step in creating a design pattern called a
Singleton.
34. OOPS Concept : Polymorphism
● Greek word means “Many forms”.
● Example Employee and Students Class inherited from Person Class
● Decision to choose right method (getDescription) at runtime from
both classes is DYNAMIC BINDING (also called function
overloading)
● Feature that allows one interface to be used for general class of
actions.
● It means it is possible to design a generic interface to a group of
related activities this helps reduce complexity by allowing the same
interface to be used to specify a general class of action, the specific
action will be selected by compiler.
35. Interface
● A way to achieve multiple inheritance.
● An interface is not a class but a set of requirements for classes that
want to conform to the interfaces.
● All methods and fields of an interface are automatically public
● Methods are not implemented in interfaces.
● An interface cannot be instantiated using new operator.
● //Interface never has instance fields.
● Instance fields or static methods are not allowed.
● There are 2 steps to make class implement an interface
– Declare that class that intends to implement the given interface.
– Supply definition to all the methods in interface.
36. Interface
//declare an interface
interface IntExample { public void sayHello(); }
public class JavaInterfaceExample implements IntExample
{
public void sayHello() { System.out.println("Hello Visitor !"); }
public static void main(String args[])
{
//create object of the class
JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
//invoke sayHello(), declared in IntExample interface.
javaInterfaceExample.sayHello();
}
}
OUTPUT : Hello Visitor !
37. Abstract Vs Interface
● Both can't in instantiated
● Both do not allow function definition in main class. (abstract class
allows if method is not tagged as abstract)
● Abstract provides single inheritance while interface multiple.
● Applying keywords : abstract (extends) | Interface (implements)
● An abstract class can have instance methods that implement a
default behavior. An Interface can only declare constants and
instance methods, but cannot implement default behavior and all
methods are implicitly abstract. An interface has all public members
and no implementation. An abstract class is a class which may have
the usual flavors of class members (private, protected, etc.), but has
some abstract methods.
38. Inner Class
● As obvious, inner class is defined inside a class
● Inner classes can be hidden from other class in same
package
● Object of an inner class can access implementation of the
object including data that would otherwise be private
● Inner classes are useful in case of callbacks on the fly
● Inner classes are useful in case event-driven programs
39. class InnerEmployee {
Inner Class public InnerEmployee
( String inName, double inSalary ) {
name = inName;
public class InnerClassTest { salary = inSalary; }
public static void main(String[] args) { private String name;
InnerEmployee lInnerEmployee = private double salary;
new InnerEmployee private String dob;
("Barak", (double)9898.9898); public void set_DOB( int d, int m, int y )
lInnerEmployee.set_DOB(1,1,1980); { DOB lDOB = new DOB ( d, m, y ); }
System.out.println public String getEmployeeRec()
(lInnerEmployee.getEmployeeRec()); { return name+" | "+salary+" | "+dob; }
} //INNER CLASS
} private class DOB {
public DOB( int d, int m, int y ) {
day=d; mon=m; year=y;
dob=""+day+"-"+mon+"-"+year;
}
private int day;
OUTPUT
private int mon;
Barak | 9898.9898 | 1-1-1980
private int year;
}
}
40. Garbage Collection
● When a reference to an object does not exist then the memory allocated to that
object is reclaimed.
● It runs automatically during program execution.
● Object destruction & finalize methods
– destruction not supported in java like C++
– finalize can be added to any method, which ensures to call garbage collector
before method call
– finalize is recommended not to use
● Java has provided some APIs to deal with garbage collection
● final is a keyword.its constant.it cant be changed from its initiated value.
● finally() {} is java block of code, used in exception handling after try{} catch(){}
block. finally(){} block will execute whether or not try block can be execute. Its
used to close a file.
● finalize() is a method, is used when an object is just before deleted,it can be used
in garbage collection.
41. Wrapper Class
● To perform operation on primitive data types, java has
provided Wrapper class
– Byte
– Short
– Integer
– Long
– Float
– Double
● Most common method : wc.parse....() and wc.toString()
42. Package, Import and Access
Modifier
● Packages are containers for classes that are used to
keep the class name space compartmentalized.
– package pkg;
● Stored in a hierarchical manner.
● More than one file can include the same package
statement.
● A hierarchy of packages can be created.
– package pkg1.pkg2.pkg3;
43. Package, Import and Access
Modifier
● Package add another dimension to access control.
● Packages and classes are both means of
encapsulation and containing the namespace and
scope of variables and methods.
● Packages act as container for classes and other
packages.
● Import statement is used for including the
packages. Syntax is
– import package.class-name;
– import package.*;
44. Exception Handling
● What is Exception Handling
● Java Support
➢ Try-catch block
➢ Throw
➢ Throws
➢ Finally
45. Exception Handling
● Some typical causes of errors
➢ Memory errors(i.e memory incorrectly
allocated,memory leaks,”null pointer”
➢ File system errors (i.e. disk is full, disk has been
removed)
➢ Network errors (i.e. network is down, URL does not
exist)
➢ Calculation errors (i.e. divide by 0)
● More typical causes of errors:
➢ Array errors (i.e. accessing element –1)
➢ Conversion errors (i.e. convert ‘q’ to a number)
➢ Can you think of some others?
46. Exception Handling
● Example
String readDataFromFile ( File inFile ) throws IOException
{
try {
... normal program code
... throw new IOException();
}
catch(Exception e) {
... exception handling code
}
catch(IOException e) {
... IO exception handling code
}
finally {
... close all files
}
}
47. Arrays and String
● Array declaration and initialization.
● String constructors.
● String conversion
● Character extraction
● String comparison
● Searching string
48. Arrays and String
Arrays
● Group of like type variables
● Can be declared in two ways
var-type var-name[];
var-name = new var-type[size];
or
var-type var-name[] = new var-type[size];
Ex. Int arr[] = new int[10];
49. Arrays and String
● Sequence of characters rather than array of
characters.
● Java implements string as object of type string.
● Support several constructors
➢ String str = new String();
➢ String str = “abc”;
➢ String(char ch[ ]) -> String initialized by an array of
characters.
● Common String function
➢ substring | equals | charAt | split | startsWith | endsWith |
indexOf | lastIndexOf |
51. Networking
● Networking
● Sockets
● Sockets for connection oriented protocol
● Sockets for connection less protocol
● Sample program of socket programming to talk
between C and Java.
52. Collection
● Collections
● List
● Array list
● Linked list
● Set
● Map
● Hash map
● Hash table
● Properties | Enumeration | StringTokenizer
● A Set is a collection that has no duplicate elements.
● A List is a collection that has an order assoicated with its elements.
● A map is a way of storing key/value pairs. The way of storing a Map is similar to two-
column table.
53. Collection
● Collection interface is the root interface of collection hierarchy.List interface is most
commonly used collection type.LinkedList and ArrayList are its well known
implementing classes.Lists can store objects only and not primitive types like int but
one can create Integer objects.All objects in List are indexed from 0 to (size of list-1)
●
● Set is very much like list but with added constraint of not storing duplicate values.Sets
do not impose a 0..size-1 indexing of the elements (that's what Lists do), so List
methods like get(int index) are not available for sets.
●
● HashSet is mostly used set which only works with elements, like String and Integer,
which have a hashCode() defined. The TreeSet is an alternative which has performance
issues, but keeps the set in sorted order, so iteration will yield the values in sorted order.
●
● java.util.Collection <-----------java.util.Map
●
● A Map is altogether different from List and Set.It stores key-value pairs and any value
can quickly be searched on the basis of a key.A map cannot contain duplicate keys;
each key can map to at most one value.'Map' is a basic interface being implemented by
classes HashMap and TreeMap.HashMap is most commonly used which can store
objects in unordered fashion while TreeMap can store in ordered fashion.Some
implementations of Map prohibit null keys and values and some have restrictions on
type of their keys.You may get NullPointerException or ClassCastException when
trying to insert or retrieve invalid keys or values.
54. Diff in Hashmap & Hashtable
● Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for
non-threaded applications, as unsynchronized Objects typically perform better than
synchronized ones.
● Hashtable does not allow null keys or values. HashMap allows one null key and any
number of null values.
● One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want
predictable iteration order (which is insertion order by default), you could easily swap
out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using
Hashtable.
● Hashtable is similar to the HashMap and has a similar interface. It is recommended that
you use HashMap unless yoou require support for legacy applications or you need
synchronisation - as the Hashtables methods are synchronised. So in your case as you
are not multi-threading, HashMaps are your best bet.
55. Database Connectivity
● JDBC(Java Database Connectivity)
● JDBC Design
● Structured Query Language
● Installing JDBC
● Basic JDBC programming concept
● Query execution
● Connection Pooling
● JDBC(Java Database Connectivity)
● Scrollable and Updatable result set
● Metadata
● How to fetch Table into ArrayList and Hashtable.
● How to populate Table from ArrayList, Hashtable, record object
58. Thread (Skip)
●Threads
●Overview
●Creation
●Synchronization
●Synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to
control the access of multiple threads to shared resources. Without
synchonization, it is possible for one thread to modify a shared variable
while another thread is in the process of using or updating same shared
variable. This usually leads to significant errors.
59. Package, Import and Access
Modifier
Private No Modifier Protected Public
Same Class Yes Yes Yes Yes
Same pkg. No Yes Yes Yes
subclass
Same pkg. No Yes Yes Yes
non subclass
Different No No Yes Yes
pkg. Subclass
Different No No No Yes
pkg. Non
subclass