SlideShare a Scribd company logo
JAVA BASIC PART II
SOUMEN SANTRA
MCA, M.Tech, SCJP, MCP
Why World Needs Java ?
Dynamic Web pages.
Platform Independent language.
Replacement of C++.
A collection of more wings.
The new programming language from Sun Microsystems.
Allows anyone to create a web page with Java code in it.
Platform Independent language
Java developer James Gosling, Arthur Van , and others.
Oak, The root of Java.
Java is “C++ -- ++ “.
Sun : Java Features
Simple and Powerful with High Performance.
Object Oriented approach.
Portable and scalable.
Independent Architecture.
Distributed based.
Multi-threaded.
Robust, Secure/Safe, No network connectivity.
Interpreted Source code.
Dynamic programming platform.
Java : OOP
Simple and easily understandable.
Flexible.
Portable
Highly effective & efficient.
Object Oriented.
Compatibility.
High Performance.
Able for Distributed Environments.
Secure.
Java as Best Object Oriented Program
Object is the key of program.
Simple and Familiar: “C++ Lite”
No Pointers overhead to the developer.
Garbage Collector.
Dynamic Binding.
Single & Multilevel Inheritance with “Interfaces”.
Java : JVM
Unicode character.
Unlike other language compilers, Java complier generates code (byte
codes) for Universal Machine.
Java Virtual Machine (JVM): Interprets bytecodes at runtime.
Independent Architecture.
No Linker.
No Loader.
No Preprocessor.
Higher Level Portable Features for GUI : AWT, Applet, Swing.
Total Platform Independence
JAVA COMPILER
JAVA BYTE CODE
JAVA INTERPRETER
Windows 95 Macintosh Solaris Windows NT
(translator)
(same for all platforms)
(one for each different system)
Java
Write Once, Run Anywhere
One Source Code In Any Platform
Java : Architecture
Java Compiler – Name javac, Converts Java source code to bytecode.
Bytecode - Machine representation Intermediate form of Source code &
native code.
JVM-A virtual machine on any target platform interprets the bytecode.
Porting the java system to any new platform involves writing an interpreter
that supports the Java Virtual Machine.
The interpreter will figure out what the equivalent machine dependent
code to run.
Java : High Performance Distributed Computing
JVM uses bytecodes.
Small binary class files.
Just-in-time Compilers.
Multithreading.
Native Methods.
Class Loader.
Lightweight Binary Class Files.
Dynamic.
Good communication constructs.
Secure.
Java : Security
Designed as safe Language.
Strict compiler javac & JIT.
Dynamic Runtime Loading verified by JVM .
Runtime Security Manager.
12
Definition of Java ?
A programming language:
Object oriented (no friends, all functions are members of classes, no function
libraries -- just class libraries).
Simple (no pointer arithmetic, no need for programmer to deallocate
memory).
 Platform Independent.
Dynamic.
Interpreted.
13
Java Data Types
Eight basic types
4 integers (byte, short, int, short) [ example : int a; ]
2 floating point (float, double) [example : double a;]
1 character (char) [example : char a; ]
1 boolean (boolean) [example : boolean a; ]
Everything else is an object
String s;
StringBuffer, StringBuilder, StringTokenizer
14
Java : Class and Object
Declaring a class
class MyClass {
member variables;
…
member functions () ;
…
} // end class MyClass
15
Java Program
Two kinds
Applications
have main() method.
run from the OS prompt (DOS OR SHELL through classpath).
Applets
have init(), start(), stop(), paint(), update(), repaint(), destroy() method.
run from within a web page using HTML <applet> tag.
16
First Java Application
class MyClass {
public static void main(String s [ ] ) {
System.out.println(“Hello World”);
}
} // end class MyClass
17
Declaring and creating objects
Declare a reference
String s;
Create/Define an object
s = new String (“Hello”); Object
Hello
StringPool
18
Java : Arrays
Arrays are objects in Java.
It is a derive object i.e. Integer based or double etc.
A homogeneous contiguous collection of elements of specific datatype.
It’s index starts with 0.
Declaration of Array:
int x [ ] ; // 1-dimensional
int [ ] x ; // 1-dimensional
int [ ] y [ ]; // 2-dimensional
int y [ ][ ];// 2-dimensional
Syntax of Array for allocate space
x = new int [5];
y = new int [5][10];
19
Java : Arrays length
It is used to retrieve the size of an array.
int a [ ] = new int [7]; // 1-dimensional
System.out.println(a.length); //output print ‘7’
int b [ ] [ ] = new int [7] [11];
System.out.println(a.length); //output print ‘7’
System.out.println(b.length * b[0].length); //output print ‘77’
Let int [][][][] array = new int [5][10][12[20] , then …
array.length * array[3rd dimensional].length * array[][2nd dimensional].length *
array[][][1st dimensional].length is 5 x 10 x 12 x 20
20
Java : Constructors
All objects are created through constructors.
Assign Object.
They are invoked automatically.
Return class type.
Mainly public for access anywhere but also private (Singleton class).
Two types: default & parameterize.
class Matter_Weight {
int lb; int oz;
public Matter_Weight (int m, int n ) {
lb = m; oz = n;
}
}
parameterize
21
Java : this keyword
Refer to as “this” local object (object in which it is used).
use:
with an instance variable or method of “this” class.
as a function inside a constructor of “this” class.
as “this” object, when passed as local parameter.
22
Java : this use Example as variable
Refers to “this” object’s data member.
class Rectangle {
int length; int breath;
public Weight (int length, int breath ) {
this. length = length; this. breath = breath;
}
}
23
Java : this use Example as method
Refers to another method of “this” class.
class Rectangle {
public int m1 (int x) {
int a = this.m2(x);
return a;
}
public int m2(int y) {
return y*7 ;
}
}// class close
24
Java : this use Example as function
It must be used with a constructor.
class Rectangle {
int length, breath;
public Rectangle (int l, int b)
{
length = a; breath = b;
}
}
public Rectangle(int m) { this( m, 0); }
}
Constructor is also overloaded
(Java allows overloading of all
methods, including constructors).
25
Java : this use Example as function object,
when passed as parameter
Refers to the object that used to call the calling method.
class MyClass {
int a;
public static void main(String [] s )
{
(new MyClass ()).Method1();
}
public void Method1()
{
Method2(this);
}
public void Method2(MyClass obj)
{ obj.a = 75; }
}
26
Java : static keyword
It means “GLOBAL” for all objects refer to the same storage.
It applies to variables or methods throughout the Program.
use:
with an instance variable of a class.
with a method of a class.
27
Java : static keyword (with variables)
class Order {
private static int OrderCount; // shared by all objects of this class throughout the program
public static void main(String [] s ) {
Order obj1 = new Order();
obj1.updateOdCount();
}
public void updateOdCount()
{
OrderCount++;
}
}
28
Java : static keyword (without methods)
class Math {
public static double sqrt(double m) {
// calculate
return result;
}
}
class MyClass{
public static void main(String [] s ) {
double d;
d = Math.sqrt(9.34);
}
}
29
Java : Inheritance (subclassing)
class Employee {
protected String name;
protected double salary;
public void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
30
Manager acts as sub/derived-class of
Employee
class Manager extends Employee {
private double bonus;
public void setBonus(double bb) {
bonus = salary * bb/100;
}
public Manager ( … ) { … }
}
31
Java : Overriding (methods)
class Manager extends Employee {
private double bonus;
public void setSalary(double bb) { …}
public void cal(double dd) {
salary += salary * dd/100 + bonus;
}
public Manager ( … ) { … }
}
Keyword for Inheritance
32
class First {
public First() { System.out.println(“ First class “); }
}
public class Second extends First {
public Second() { System.out.println(“Second class”); }
}
public class Third extends Second {
public Third() {System.out.println(“Third class”);}
}
Java : Role of Constructors in
Inheritance
First class
Second class
Third class
Topmost class constructor is invoked first
(like us …grandparent-->parent-->child->)
33
Java : Access Modifiers
private
Same class only
public
Everywhere
protected
Same class, Same package, any subclass
(default)
Same class, Same package
34
Java : super keyword
Refers to the superclass (base class)
use:
with a variable or method (most common with a method)
as a function inside a constructor of the subclass
35
Java : super with a method
class Manager extends Employee {
private double bonus;
public void setSalary(double bb) { …}
public void cal(double dd) { //overrides cal() of Employee
super.cal(dd); // call Employee’s cal()
salary += bonus;
}
public Manager ( … ) { … }
}
36
Java : super function inside a constructor of the subclass
class Manager extends Employee {
private double bonus;
public void setSalary(double bb) { …}
public Manager ( String name, double salary, double bonus )
{
super(name, salary);
this.bonus = bonus;
}
}
37
Java : final keyword
It means “constant”.
It applies to
variables (makes a constant variable), or
methods (makes a non-overridable or final method)
or
classes (makes a class non-overridable or final means
“objects cannot be created”).
38
Java : final keyword with a variable
class Math {
public final double pi = 3.141;
public static double cal(double x) {
double x = pi * pi;
}
}
note: variable pi is made “Not Overriden”
39
Java : final keyword with a method
class Employee {
protected String name;
protected double salary;
public final void cal(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
Cannot override final method cal() inside the Manager
class
40
Java : final keyword with a class
final class Employee {
protected String name;
protected double salary;
public void cal(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
Not create class Manager as a subclass of class Employee
(all are equal)
41
Java : abstract classes and interfaces
abstract classes
may have both implemented and non-implemented methods.
interfaces
have only non-implemented methods.
(concrete classes or pure classes)
have all their methods implemented.
42
Java : abstract class
abstract class Figure {
public abstract double area();
public abstract double perimeter();
public abstract void print();
public void setOutColor(Color cc) {
// code to set the color
}
public void setInColor(Color cc) {
// code to set the color
}
}
KEYWORD FOR
ABSTRACT
CLASS
43
Java : interface
interface MouseClick {
public void Down();
public void Up();
public void DoubleClick();
}
class PureClick implements Mouse Click {
// all above methods implemented here
}
KEYWORD FOR
INTERFACE
CLASS
44
Java : Exceptions (error handling)
code without exceptions:
...
int x = 7, y = 0, result;
if ( y != 0) {
result = x/y;
}
else {
System.out.println(“y is zero”);
}
...
code with exceptions:
...
int x = 7, y = 0, result;
try {
result = x/y;
}
catch (ArithmeticException ex )
{
System.out.println(“y is zero”);
}
...
A nice way to handle errors in Java programs
45
Java : Exceptions (try-catch-finally block )
import java.io.*;
class Test{
public static void main(String args[]){
int x = 7, y = 0, result;
try {
result = x/y;
/// more code .. Main operations
}
catch (ArithmeticException ex1 ) {
System.out.println(“y is zero”);
}
catch (IOException ex2 ) {
System.out.println(“Can’t read Format error”);
}
finally {
System.out.println(“Closing file”);
/// code to close file, release memory.
}
}}
KEYWORD FOR
Exception CLASS
Package FOR
Exception
CLASS
46
Java : Using Throwing Exceptions
public int divide (int x, int y ) throws ArithmeticException {
if (y == 0 ) {
throw new ArithmeticException();
}
else {
return x/y ;
}
} // end divide()
KEYWORD FOR
Exception CLASS
47
Java : User Defining exceptions
public int divide (int x, int y ) throws MyException {
if (y == 0 ) {
throw new MyException();
}
else {
return a/b ;
}
} // end divide()
}
import java.io.*;
class MyException extends ArithmeticException
{
KEYWORD FOR
Exception CLASS
Package FOR
Exception
CLASS
inherit
Exception
CLASS
THANK YOU
GIVE FEEDBACK

More Related Content

What's hot

Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
tosine
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of features
vidyamittal
 
Lecture 13, 14 & 15 c# cmd let programming and scripting
Lecture 13, 14 & 15   c# cmd let programming and scriptingLecture 13, 14 & 15   c# cmd let programming and scripting
Lecture 13, 14 & 15 c# cmd let programming and scripting
Wiliam Ferraciolli
 
Java class 3
Java class 3Java class 3
Java class 3
Edureka!
 

What's hot (20)

Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Python advance
Python advancePython advance
Python advance
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of features
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Lecture 13, 14 & 15 c# cmd let programming and scripting
Lecture 13, 14 & 15   c# cmd let programming and scriptingLecture 13, 14 & 15   c# cmd let programming and scripting
Lecture 13, 14 & 15 c# cmd let programming and scripting
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java class 3
Java class 3Java class 3
Java class 3
 

Similar to Java basic part 2 : Datatypes Keywords Features Components Security Exceptions

Similar to Java basic part 2 : Datatypes Keywords Features Components Security Exceptions (20)

basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Java notes
Java notesJava notes
Java notes
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptxJAVA INETRNSHIP1 made with simple topics.ppt.pptx
JAVA INETRNSHIP1 made with simple topics.ppt.pptx
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
 
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUCDevelopment of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 

More from Soumen Santra

More from Soumen Santra (20)

Cell hole identification in carcinogenic segment using Geodesic Methodology: ...
Cell hole identification in carcinogenic segment using Geodesic Methodology: ...Cell hole identification in carcinogenic segment using Geodesic Methodology: ...
Cell hole identification in carcinogenic segment using Geodesic Methodology: ...
 
PPT_PAPERID 31_SOUMEN_SANTRA - ICCET23.pptx
PPT_PAPERID 31_SOUMEN_SANTRA - ICCET23.pptxPPT_PAPERID 31_SOUMEN_SANTRA - ICCET23.pptx
PPT_PAPERID 31_SOUMEN_SANTRA - ICCET23.pptx
 
Basic networking hardware: Switch : Router : Hub : Bridge : Gateway : Bus : C...
Basic networking hardware: Switch : Router : Hub : Bridge : Gateway : Bus : C...Basic networking hardware: Switch : Router : Hub : Bridge : Gateway : Bus : C...
Basic networking hardware: Switch : Router : Hub : Bridge : Gateway : Bus : C...
 
Traveling salesman problem: Game Scheduling Problem Solution: Ant Colony Opti...
Traveling salesman problem: Game Scheduling Problem Solution: Ant Colony Opti...Traveling salesman problem: Game Scheduling Problem Solution: Ant Colony Opti...
Traveling salesman problem: Game Scheduling Problem Solution: Ant Colony Opti...
 
Optimization techniques: Ant Colony Optimization: Bee Colony Optimization: Tr...
Optimization techniques: Ant Colony Optimization: Bee Colony Optimization: Tr...Optimization techniques: Ant Colony Optimization: Bee Colony Optimization: Tr...
Optimization techniques: Ant Colony Optimization: Bee Colony Optimization: Tr...
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Merge sort
Merge sortMerge sort
Merge sort
 
A Novel Real Time Home Automation System with Google Assistance Technology
A Novel Real Time Home Automation System with Google Assistance TechnologyA Novel Real Time Home Automation System with Google Assistance Technology
A Novel Real Time Home Automation System with Google Assistance Technology
 
Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
 
Frequency Division Multiplexing Access (FDMA)
Frequency Division Multiplexing Access (FDMA)Frequency Division Multiplexing Access (FDMA)
Frequency Division Multiplexing Access (FDMA)
 
Carrier Sense Multiple Access With Collision Detection (CSMA/CD) Details : Me...
Carrier Sense Multiple Access With Collision Detection (CSMA/CD) Details : Me...Carrier Sense Multiple Access With Collision Detection (CSMA/CD) Details : Me...
Carrier Sense Multiple Access With Collision Detection (CSMA/CD) Details : Me...
 
Code-Division Multiple Access (CDMA)
Code-Division Multiple Access (CDMA)Code-Division Multiple Access (CDMA)
Code-Division Multiple Access (CDMA)
 
PURE ALOHA : MEDIUM ACCESS CONTROL PROTOCOL (MAC): Definition : Types : Details
PURE ALOHA : MEDIUM ACCESS CONTROL PROTOCOL (MAC): Definition : Types : DetailsPURE ALOHA : MEDIUM ACCESS CONTROL PROTOCOL (MAC): Definition : Types : Details
PURE ALOHA : MEDIUM ACCESS CONTROL PROTOCOL (MAC): Definition : Types : Details
 
Carrier-sense multiple access with collision avoidance CSMA/CA
Carrier-sense multiple access with collision avoidance CSMA/CACarrier-sense multiple access with collision avoidance CSMA/CA
Carrier-sense multiple access with collision avoidance CSMA/CA
 
RFID (RADIO FREQUENCY IDENTIFICATION)
RFID (RADIO FREQUENCY IDENTIFICATION)RFID (RADIO FREQUENCY IDENTIFICATION)
RFID (RADIO FREQUENCY IDENTIFICATION)
 
SPACE DIVISION MULTIPLE ACCESS (SDMA) SATELLITE COMMUNICATION
SPACE DIVISION MULTIPLE ACCESS (SDMA) SATELLITE COMMUNICATION  SPACE DIVISION MULTIPLE ACCESS (SDMA) SATELLITE COMMUNICATION
SPACE DIVISION MULTIPLE ACCESS (SDMA) SATELLITE COMMUNICATION
 
Threads Basic : Features, Types & Implementation
Threads Basic : Features, Types  & ImplementationThreads Basic : Features, Types  & Implementation
Threads Basic : Features, Types & Implementation
 
CLOUD COMPUTING : BASIC CONCEPT REGARDING LOAD BALANCING AND Virtual Machine ...
CLOUD COMPUTING : BASIC CONCEPT REGARDING LOAD BALANCING AND Virtual Machine ...CLOUD COMPUTING : BASIC CONCEPT REGARDING LOAD BALANCING AND Virtual Machine ...
CLOUD COMPUTING : BASIC CONCEPT REGARDING LOAD BALANCING AND Virtual Machine ...
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
 

Recently uploaded

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 

Java basic part 2 : Datatypes Keywords Features Components Security Exceptions

  • 1. JAVA BASIC PART II SOUMEN SANTRA MCA, M.Tech, SCJP, MCP
  • 2. Why World Needs Java ? Dynamic Web pages. Platform Independent language. Replacement of C++. A collection of more wings. The new programming language from Sun Microsystems. Allows anyone to create a web page with Java code in it. Platform Independent language Java developer James Gosling, Arthur Van , and others. Oak, The root of Java. Java is “C++ -- ++ “.
  • 3. Sun : Java Features Simple and Powerful with High Performance. Object Oriented approach. Portable and scalable. Independent Architecture. Distributed based. Multi-threaded. Robust, Secure/Safe, No network connectivity. Interpreted Source code. Dynamic programming platform.
  • 4. Java : OOP Simple and easily understandable. Flexible. Portable Highly effective & efficient. Object Oriented. Compatibility. High Performance. Able for Distributed Environments. Secure.
  • 5. Java as Best Object Oriented Program Object is the key of program. Simple and Familiar: “C++ Lite” No Pointers overhead to the developer. Garbage Collector. Dynamic Binding. Single & Multilevel Inheritance with “Interfaces”.
  • 6. Java : JVM Unicode character. Unlike other language compilers, Java complier generates code (byte codes) for Universal Machine. Java Virtual Machine (JVM): Interprets bytecodes at runtime. Independent Architecture. No Linker. No Loader. No Preprocessor. Higher Level Portable Features for GUI : AWT, Applet, Swing.
  • 7. Total Platform Independence JAVA COMPILER JAVA BYTE CODE JAVA INTERPRETER Windows 95 Macintosh Solaris Windows NT (translator) (same for all platforms) (one for each different system)
  • 8. Java Write Once, Run Anywhere One Source Code In Any Platform
  • 9. Java : Architecture Java Compiler – Name javac, Converts Java source code to bytecode. Bytecode - Machine representation Intermediate form of Source code & native code. JVM-A virtual machine on any target platform interprets the bytecode. Porting the java system to any new platform involves writing an interpreter that supports the Java Virtual Machine. The interpreter will figure out what the equivalent machine dependent code to run.
  • 10. Java : High Performance Distributed Computing JVM uses bytecodes. Small binary class files. Just-in-time Compilers. Multithreading. Native Methods. Class Loader. Lightweight Binary Class Files. Dynamic. Good communication constructs. Secure.
  • 11. Java : Security Designed as safe Language. Strict compiler javac & JIT. Dynamic Runtime Loading verified by JVM . Runtime Security Manager.
  • 12. 12 Definition of Java ? A programming language: Object oriented (no friends, all functions are members of classes, no function libraries -- just class libraries). Simple (no pointer arithmetic, no need for programmer to deallocate memory).  Platform Independent. Dynamic. Interpreted.
  • 13. 13 Java Data Types Eight basic types 4 integers (byte, short, int, short) [ example : int a; ] 2 floating point (float, double) [example : double a;] 1 character (char) [example : char a; ] 1 boolean (boolean) [example : boolean a; ] Everything else is an object String s; StringBuffer, StringBuilder, StringTokenizer
  • 14. 14 Java : Class and Object Declaring a class class MyClass { member variables; … member functions () ; … } // end class MyClass
  • 15. 15 Java Program Two kinds Applications have main() method. run from the OS prompt (DOS OR SHELL through classpath). Applets have init(), start(), stop(), paint(), update(), repaint(), destroy() method. run from within a web page using HTML <applet> tag.
  • 16. 16 First Java Application class MyClass { public static void main(String s [ ] ) { System.out.println(“Hello World”); } } // end class MyClass
  • 17. 17 Declaring and creating objects Declare a reference String s; Create/Define an object s = new String (“Hello”); Object Hello StringPool
  • 18. 18 Java : Arrays Arrays are objects in Java. It is a derive object i.e. Integer based or double etc. A homogeneous contiguous collection of elements of specific datatype. It’s index starts with 0. Declaration of Array: int x [ ] ; // 1-dimensional int [ ] x ; // 1-dimensional int [ ] y [ ]; // 2-dimensional int y [ ][ ];// 2-dimensional Syntax of Array for allocate space x = new int [5]; y = new int [5][10];
  • 19. 19 Java : Arrays length It is used to retrieve the size of an array. int a [ ] = new int [7]; // 1-dimensional System.out.println(a.length); //output print ‘7’ int b [ ] [ ] = new int [7] [11]; System.out.println(a.length); //output print ‘7’ System.out.println(b.length * b[0].length); //output print ‘77’ Let int [][][][] array = new int [5][10][12[20] , then … array.length * array[3rd dimensional].length * array[][2nd dimensional].length * array[][][1st dimensional].length is 5 x 10 x 12 x 20
  • 20. 20 Java : Constructors All objects are created through constructors. Assign Object. They are invoked automatically. Return class type. Mainly public for access anywhere but also private (Singleton class). Two types: default & parameterize. class Matter_Weight { int lb; int oz; public Matter_Weight (int m, int n ) { lb = m; oz = n; } } parameterize
  • 21. 21 Java : this keyword Refer to as “this” local object (object in which it is used). use: with an instance variable or method of “this” class. as a function inside a constructor of “this” class. as “this” object, when passed as local parameter.
  • 22. 22 Java : this use Example as variable Refers to “this” object’s data member. class Rectangle { int length; int breath; public Weight (int length, int breath ) { this. length = length; this. breath = breath; } }
  • 23. 23 Java : this use Example as method Refers to another method of “this” class. class Rectangle { public int m1 (int x) { int a = this.m2(x); return a; } public int m2(int y) { return y*7 ; } }// class close
  • 24. 24 Java : this use Example as function It must be used with a constructor. class Rectangle { int length, breath; public Rectangle (int l, int b) { length = a; breath = b; } } public Rectangle(int m) { this( m, 0); } } Constructor is also overloaded (Java allows overloading of all methods, including constructors).
  • 25. 25 Java : this use Example as function object, when passed as parameter Refers to the object that used to call the calling method. class MyClass { int a; public static void main(String [] s ) { (new MyClass ()).Method1(); } public void Method1() { Method2(this); } public void Method2(MyClass obj) { obj.a = 75; } }
  • 26. 26 Java : static keyword It means “GLOBAL” for all objects refer to the same storage. It applies to variables or methods throughout the Program. use: with an instance variable of a class. with a method of a class.
  • 27. 27 Java : static keyword (with variables) class Order { private static int OrderCount; // shared by all objects of this class throughout the program public static void main(String [] s ) { Order obj1 = new Order(); obj1.updateOdCount(); } public void updateOdCount() { OrderCount++; } }
  • 28. 28 Java : static keyword (without methods) class Math { public static double sqrt(double m) { // calculate return result; } } class MyClass{ public static void main(String [] s ) { double d; d = Math.sqrt(9.34); } }
  • 29. 29 Java : Inheritance (subclassing) class Employee { protected String name; protected double salary; public void raise(double dd) { salary += salary * dd/100; } public Employee ( … ) { … } }
  • 30. 30 Manager acts as sub/derived-class of Employee class Manager extends Employee { private double bonus; public void setBonus(double bb) { bonus = salary * bb/100; } public Manager ( … ) { … } }
  • 31. 31 Java : Overriding (methods) class Manager extends Employee { private double bonus; public void setSalary(double bb) { …} public void cal(double dd) { salary += salary * dd/100 + bonus; } public Manager ( … ) { … } } Keyword for Inheritance
  • 32. 32 class First { public First() { System.out.println(“ First class “); } } public class Second extends First { public Second() { System.out.println(“Second class”); } } public class Third extends Second { public Third() {System.out.println(“Third class”);} } Java : Role of Constructors in Inheritance First class Second class Third class Topmost class constructor is invoked first (like us …grandparent-->parent-->child->)
  • 33. 33 Java : Access Modifiers private Same class only public Everywhere protected Same class, Same package, any subclass (default) Same class, Same package
  • 34. 34 Java : super keyword Refers to the superclass (base class) use: with a variable or method (most common with a method) as a function inside a constructor of the subclass
  • 35. 35 Java : super with a method class Manager extends Employee { private double bonus; public void setSalary(double bb) { …} public void cal(double dd) { //overrides cal() of Employee super.cal(dd); // call Employee’s cal() salary += bonus; } public Manager ( … ) { … } }
  • 36. 36 Java : super function inside a constructor of the subclass class Manager extends Employee { private double bonus; public void setSalary(double bb) { …} public Manager ( String name, double salary, double bonus ) { super(name, salary); this.bonus = bonus; } }
  • 37. 37 Java : final keyword It means “constant”. It applies to variables (makes a constant variable), or methods (makes a non-overridable or final method) or classes (makes a class non-overridable or final means “objects cannot be created”).
  • 38. 38 Java : final keyword with a variable class Math { public final double pi = 3.141; public static double cal(double x) { double x = pi * pi; } } note: variable pi is made “Not Overriden”
  • 39. 39 Java : final keyword with a method class Employee { protected String name; protected double salary; public final void cal(double dd) { salary += salary * dd/100; } public Employee ( … ) { … } } Cannot override final method cal() inside the Manager class
  • 40. 40 Java : final keyword with a class final class Employee { protected String name; protected double salary; public void cal(double dd) { salary += salary * dd/100; } public Employee ( … ) { … } } Not create class Manager as a subclass of class Employee (all are equal)
  • 41. 41 Java : abstract classes and interfaces abstract classes may have both implemented and non-implemented methods. interfaces have only non-implemented methods. (concrete classes or pure classes) have all their methods implemented.
  • 42. 42 Java : abstract class abstract class Figure { public abstract double area(); public abstract double perimeter(); public abstract void print(); public void setOutColor(Color cc) { // code to set the color } public void setInColor(Color cc) { // code to set the color } } KEYWORD FOR ABSTRACT CLASS
  • 43. 43 Java : interface interface MouseClick { public void Down(); public void Up(); public void DoubleClick(); } class PureClick implements Mouse Click { // all above methods implemented here } KEYWORD FOR INTERFACE CLASS
  • 44. 44 Java : Exceptions (error handling) code without exceptions: ... int x = 7, y = 0, result; if ( y != 0) { result = x/y; } else { System.out.println(“y is zero”); } ... code with exceptions: ... int x = 7, y = 0, result; try { result = x/y; } catch (ArithmeticException ex ) { System.out.println(“y is zero”); } ... A nice way to handle errors in Java programs
  • 45. 45 Java : Exceptions (try-catch-finally block ) import java.io.*; class Test{ public static void main(String args[]){ int x = 7, y = 0, result; try { result = x/y; /// more code .. Main operations } catch (ArithmeticException ex1 ) { System.out.println(“y is zero”); } catch (IOException ex2 ) { System.out.println(“Can’t read Format error”); } finally { System.out.println(“Closing file”); /// code to close file, release memory. } }} KEYWORD FOR Exception CLASS Package FOR Exception CLASS
  • 46. 46 Java : Using Throwing Exceptions public int divide (int x, int y ) throws ArithmeticException { if (y == 0 ) { throw new ArithmeticException(); } else { return x/y ; } } // end divide() KEYWORD FOR Exception CLASS
  • 47. 47 Java : User Defining exceptions public int divide (int x, int y ) throws MyException { if (y == 0 ) { throw new MyException(); } else { return a/b ; } } // end divide() } import java.io.*; class MyException extends ArithmeticException { KEYWORD FOR Exception CLASS Package FOR Exception CLASS inherit Exception CLASS

Editor's Notes

  1. 1