This document provides an overview of the Java programming language as presented by Ms. Surbhi Saroha. It covers topics such as Java overview, data types, control structures, arrays, strings, classes, inheritance, packages, exceptions, and more. The document contains slides with explanations, examples, and code snippets to illustrate key concepts of the Java language.
3. Java – Overview
Java programming language was
originally developed by Sun
Microsystems which was initiated by
James Gosling and released in 1995.
The latest release of the Java Standard
Edition is Java SE 8.
Java is guaranteed to be Write Once,
Run Anywhere .
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 3
4. Java is:
Object Oriented: In Java, everything is an Object. Java can
be easily extended since it is based on the Object model.
Platform Independent: Unlike many other programming
languages including C and C++, when Java is compiled, it
is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you
understand the basic concept of OOP Java, it would be
easy to master.
Secure: With Java's secure feature it enables to develop
virus-free, tamper-free systems. Authentication techniques
are based on public-key encryption.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 4
5. Cont…..
Architecture-neutral: Java compiler generates an architecture-
neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java
runtime system.
Portable: Being architecture-neutral and having no
implementation dependent aspects of the specification makes
Java portable.
Robust: Java makes an effort to eliminate error prone situations
by emphasizing mainly on compile time error checking and
runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 5
6. Cont…
Interpreted: Java byte code is translated on the fly to native
machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance: With the use of Just-In-Time compilers,
Java enables high performance.
Distributed: Java is designed for the distributed
environment of the internet.
Dynamic: Java is considered to be more dynamic than C or
C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of
run-time information that can be used to verify and resolve
accesses to objects on run-time.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 6
7. First Java Program
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints
Hello World
}
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 7
8. Setting Up the Path for
Windows
Assuming you have installed Java in
c:Program Filesjavajdk directory:
Right-click on 'My Computer' and select
'Properties'.
Click the 'Environment variables' button under
the 'Advanced' tab.
Now, alter the 'Path' variable so that it also
contains the path to the Java executable.
Example, if the path is currently set to
'C:WINDOWSSYSTEM32', then change your
path to read
'C:WINDOWSSYSTEM32;c:Program
Filesjavajdkbin
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 8
9. Save the file, compile and run
the program
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and
. Java – Basic Syntax
go to the directory where you saved the
class. Assume it's C:.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 9
10. Cont….
Type 'javac MyFirstJavaProgram.java' and
press enter to compile your code. If there are
no errors in your code, the command prompt
will take you to the next line (Assumption : The
path variable is set).
Now, type ' java MyFirstJavaProgram ' to run
your program.
You will be able to see ' Hello World ' printed
on the window.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 10
11. Cont….
C:> javac MyFirstJavaProgram.java
C:> java MyFirstJavaProgram
Hello World
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 11
12. Basic Syntax
Case Sensitivity - Java is case sensitive, which means identifier Helloand hello
would have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.
Example: class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name - Name of the program file should exactly match the class
name. When saving the file, you should save it using the class name (Remember
Java is case sensitive) and append '.java' to the end of the name (if the file name
and the class name do not match, your program will not compile). Example:
Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 12
13. Java is an Object-Oriented
Language
Java supports the following fundamental
concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 13
14. Classes in Java
A class is a blueprint from which individual objects
are created.
public class Dog{
String breed;
int ageC
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 14
15. Constructors
The main rule of constructors is that they should
have the same name as the class. A class can have
more than one constructor.
Following is an example of a constructor:
public class Puppy{
public Puppy(){
}
public Puppy(String name){
// This constructor has one parameter, name.
}
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 15
16. Basic Datatypes
There are two data types available in
Java:
Primitive Datatypes
Reference/Object Datatypes
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 16
17. Primitive Datatypes
Byte
short
int
long
float
double
boolean
char
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 17
18. Reference Datatypes
A reference variable can be used to
refer any object of the declared type or
any compatible type.
Example: Animal animal = new
Animal("giraffe");
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 18
19. Java Access Modifiers
The four access levels are:
Visible to the package, the default. No
modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all
subclasses (protected).
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 19
20. Abstract Class
An abstract class can never be
instantiated. If a class is declared as
abstract then the sole purpose is for the
class to be extended.
A class cannot be both abstract and final
(since a final class cannot be extended). If
a class contains abstract methods then the
class should be declared abstract.
Otherwise, a compile error will be thrown.
An abstract class may contain both
abstract methods as well normal methods.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 20
21. Example
abstract class Caravan{
private double price;
private String model;
private String year;
public abstract void goFast(); //an
abstract method
public abstract void changeColor();
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 21
25. Strings Class
Strings, which are widely used in Java
programming, are a sequence of
characters.
Creating Strings
The most direct way to create a string is
to write:
String greeting = "Hello world!";
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 25
26. Example
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new
String(helloArray);
System.out.println( helloString );
}
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 26
27. Output
This will produce the following result:
hello.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 27
28. String Length
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " +
len );
}
}
This will produce the following result:
String Length is : 17
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 28
29. Concatenating Strings
String compareTo(String anotherString)
Method
The String class includes a method for
concatenating two strings:
string1.concat(string2);
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 29
30. Arrays
Java provides a data structure, the
array, which stores a fixed-size
sequential collection of elements of the
same type.
An array is used to store a collection of
data, but it is often more useful to think
of an array as a collection of variables of
the same type.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 30
31. Java – Exceptions
An exception (or exceptional event) is a
problem that arises during the execution
of a program. When an Exception
occurs the normal flow of the program is
disrupted and the program/Application
terminates abnormally, which is not
recommended, therefore, these
exceptions are to be handled.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 31
33. Catching Exceptions
A method catches an exception using a
combination of the try and catch
keywords.
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 33
34. Java – Inner Classes
Nested Classes
In Java, just like methods, variables of a
class too can have another class as its
member. Writing a class within another
is allowed in Java. The class written
within is called the nested class, and
the class that holds the inner class is
called the outer class.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 34
35. Syntax to write a nested
class
Here, the class Outer_Demo is the
outer class and the class Inner_Demo
is the nested class.
class Outer_Demo{
class Nested_Demo{
}
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 35
36. Java – Inheritance
The class which inherits the properties
of other is known as subclass (derived
class, child class) and the class whose
properties are inherited is known as
superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit
the properties of a class. Following is
the syntax of extends keyword.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 36
37. Syntax of extends keyword
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 37
40. Note:-
A very important fact to remember is that
Java does not support multiple
inheritance. This means that a class
cannot extend more than one class.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 40
41. Java – Packages
A Package can be defined as a grouping
of related types (classes, interfaces,
enumerations and annotations )
providing access protection and
namespace management.
Some of the existing packages in Java are:
java.lang - bundles the fundamental
classes
java.io - classes for input, output
functions are bundled in this package
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 41
42. Creating a Package
While creating a package, you should
choose a name for the package and
include a package statement along with
that name at the top of every source file
that contains the classes, interfaces,
enumerations, and annotation types
that you want to include in the package.
The package statement should be the first
line in the source file. There can be only
one package statement in each source file,
and it applies to all types in the file.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 42
43. Package example
Following package example contains
interface named animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 43
44. Exception Handling
A Java exception is an object that
describes an exceptional (that is, error)
condition that has occurred in a piece of
code.
Java exception handling is managed via
five keywords: try, catch, throw,
throws, and finally.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 44
45. General form of an exception-
handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 45
46. Multithreaded Programming
Unlike many other computer languages,
Java provides built-in support for
multithreaded programming. A
multithreaded program contains two or
more parts that can run concurrently.
Each part of such a program is called a
thread, and each thread defines
a separate path of execution. Thus,
multithreading is a specialized form of
multitasking.
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 46
47. Creating Multiple Threads
// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 47
48. Cont….
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 48
49. Cont….
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
7/14/2017 Ms SURBHI SAROHA(Asst.Professor) 49