0% found this document useful (0 votes)
10 views

java unit-1 final (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

java unit-1 final (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Programming with JAVA

Prepared By:
Dr. Nidhi H. Divecha

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 1


Learning Objectives
• To learn why Java is useful for desktop and web applications.

• To learn how to implement object-oriented designs with Java.

• To identify Java language components and how they work together


in
• applications.

• To design and program stand-alone Java applications.

• To learn how to extend Java classes with inheritance.

• To learn how to use exception handling in Java applications.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 2


What is Java?
• Java is a programming language and a computing platform for
application development.

• Java is a high level, robust, object-oriented and secure


programming language.

• It was first released by Sun Microsystem in 1995 and later acquired


by Oracle Corporation.

• James Gosling is known as the father of Java. Before Java, its name
was Oak. Since Oak was already a registered company, so James
Gosling and his team changed the name from Oak to Java.

• Platform: Any hardware or software environment in which a


program runs, is known as a platform. Since Java has a runtime
environment (JRE) and API, it is called a platform.
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 3
Application
According to Sun, 6 billion devices run Java. There are many devices
where Java is currently used. Some of them are as follows:

It is used for:

• Mobile applications (specially Android apps).


• Desktop applications such as acrobat reader, media player, antivirus, etc.
• Web applications such as irctc.co.in, javatpoint.com, etc.
• Web servers and application servers.
• Enterprise Applications such as banking applications.
• Embedded Systems.
• Smart Card.
• Robotics.
• Games.

And much, much more!

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 4


Java Platforms / Editions
There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


It is a Java programming platform. It includes Java programming APIs such as
java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics
like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)


It is an enterprise platform that is mainly used to develop web and enterprise
applications. It is built on top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)


It is a micro platform that is dedicated to mobile applications.

4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user
interface API.
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 5
Types of Java Applications
There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application
Standalone applications are also known as desktop applications or
window-based applications. These are traditional software that we
need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic
page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 6


Types of Java Applications
3) Enterprise Application
An application that is distributed in nature, such as
banking applications, etc. is called an enterprise
application. It has advantages like high-level security,
load balancing, and clustering. In Java, EJB is used for
creating enterprise applications.

4) Mobile Application
An application which is created for mobile devices is
called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 7
How to run
• JDK – Java Development Kit
– Basic compiler, linker, and libraries

• JRE – Java Runtime Environment


– It is the implementation of JVM, Predefined set of java classes
available to use

• JVM – Java Virtual Machine


– Loads, verifies and executes code

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 8


What is JVM?
• JVM, i.e., Java Virtual Machine.
• Java compiler produce an intermediate code known as byte code
for a machine that does not exist physically is called Java Virtual
Machine and it is exist only inside the computer memory
• JVM is a part of Java Run Environment (JRE).
• Mostly in other Programming Languages, compiler produce code
for a particular system but Java compiler produce Bytecode for a
Java Virtual Machine.
• When we compile a Java program, then bytecode is generated.
Bytecode is the source code that can be used to run on any
platform.
• JVM is the medium which compiles Java code to bytecode which
gets interpreted on a different machine and hence it makes it
Platform/Operating system independent.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 9


How JVM Works?
• First, Java code is compiled into bytecode. This bytecode gets
interpreted on different machines.

• Between host system and Java source, Bytecode is an intermediary


language.

• JVM in Java is responsible for allocating memory space.

Working of Java Virtual Machine (JVM)

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 10


JVM Architecture
Now in this JVM tutorial, let’s understand the Architecture of JVM. JVM
architecture in Java contains classloader, memory area, execution engine etc.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 11


• NOTE: JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM).

• In Java, the Just In Time Code generator interprers the bytecode into the native
machine code which are at the same programming levels at the same time.

• Hence, Java is both compiled as well as interpreted language.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 12


What is JRE?
• JRE (Java Runtime Environment) is a software
package that provides Java class libraries, Java
Virtual Machine (JVM), and other components
that are required to run Java applications.
• JRE is the superset of JVM.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 13


Java Development Kit (JDK)
• JDK is for Java Development Kit. The Java Development
Kit (JDK) is a software development environment which
is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.

• The JDK contains a private Java Virtual Machine (JVM)


and a few other resources such as follows

1. Appletviewer (for viewing java applets)


2. Javac (Java compiler)
3. Java (java interpreter)
4. Javap (java disassemble which enables us to convert
bytecode files into a program description)
5. Javah (Produces header files for use with native
methods)
6. Javadoc (creates HTML format documentation from
Java source code files)
7. Jdb ( Java debugger, which helps us to find errors in
our programs)

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 14


Features of Java
• The features of Java are also known as Java buzzwords. A list of the
most important features of the Java language is given below.
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 15
Simple
• Java is very easy to learn, and its syntax is simple, clean and
easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:

• Java syntax is based on C++ (so easier for programmers to


learn it after C++).

• Java has removed many complicated and rarely-used


features, for example, explicit pointers, operator
overloading, etc.

• There is no need to remove unreferenced objects because


there is an Automatic Garbage Collection in Java.
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 16
Object-oriented
• Java is an object-oriented programming language.

• Everything in Java is an object.

• Object-oriented programming (OOPs) is a methodology that simplifies


software development and maintenance by providing some rules.

• Basic concepts of OOPs are:


• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 17


Platform Independent
• Java is platform independent as Java code is compiled by
the compiler and converted into bytecode.

• This bytecode is a platform-independent code because it


can be run on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc.

• Java is a Write Once and Run Anywhere (WORA).

• The Java platform differs from most other platforms in


the sense that it is a software-based platform that runs
on top of other hardware-based platforms. It has two
components:
– Runtime Environment
– API(Application Programming Interface)

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 18


Secured
• Java is best known for its security. With Java, we can
develop virus-free systems. Java is secured because:

• No explicit pointer
• Java Programs run inside a virtual machine sandbox

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 19


Robust
The English mining of Robust is strong. Java is robust
because:
– It uses strong memory management.

– There is a lack of pointers that avoids security problems.

– Java provides automatic garbage collection.

– There are exception handling and the type checking


mechanism in Java.
All these points make Java robust.
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 20
Architecture-neutral
• Java is architecture neutral because there are no
implementation dependent features, for
example, the size of primitive types is fixed.

• In C programming, int data type occupies 2 bytes


of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture.

• However, it occupies 4 bytes of memory for both


32 and 64-bit architectures in Java.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 21


Portable
• Java is portable because it facilitates you to
carry the Java bytecode to any platform.

• It doesn't require any implementation.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 22


High-performance
• Java is faster than other traditional interpreted
programming languages because Java bytecode is
"close" to native code.

• It is still a little bit slower than a compiled


language (e.g., C++).

• Java is an interpreted language that is why it is


slower than compiled languages, e.g., C, C++, etc.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 23


Distributed
• Java is distributed because it facilitates users
to create distributed applications in Java.

• RMI and EJB are used for creating distributed


applications.

• This feature of Java makes us able to access


files by calling the methods from any machine
on the internet.
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 24
Multi-threaded
• A thread is like a separate program, executing concurrently.

• We can write Java programs that deal with many tasks at


once by defining multiple threads.

• The main advantage of multi-threading is that it doesn't


occupy memory for each thread. It shares a common
memory area.

• Threads are important for multi-media, Web applications,


etc.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 25


Dynamic
• Java is a dynamic language, as it supports the
dynamic loading of classes.

• It means classes are loaded on demand. It also


supports functions from its native languages, i.e.,
C and C++.

• Java supports dynamic compilation and


automatic memory management (garbage
collection).

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 26


How Java differs from C and C++

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 27


19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 28
Documentation Section
• It consists of comments in Java which include basic information related to program
for the programmer to understand it while reviewing or debugging the code.
• A Java comment can appear anywhere in the code.

• There are three types of comments that Java supports

• Single line Comment


// a single line comment is declared like this

• Multi-line Comment
/* a multi-line comment is declared like this
and can have multiple lines as a comment */

• Documentation Comment
/** a documentation comment starts with a delimiter and end with */

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 29


Package Statement
• There can be only one package statement in a Java
program and it has to be at the beginning of the code
before any class or interface declaration.

• In this section, we declare the package name in which the


class is placed.

• The keyword package to declare the package name. For


example:

1. package student;
2. package employee;

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 30


Import Statement
• To use any class of a particular package, we need to import that class.

• To import a specific class or classes in an import statement the import keyword is


used.

• An import statement is always written after the package statement but it has to be
before any class declaration.

• We use the import statement in two ways,


• import a specific class
• import all classes of a particular package.

• In a Java program, we can use multiple import statements. For example:

import java.util.Date; //imports the date class only


import java.util.*; //imports all the classes from the java util package
import java.applet.*; //imports all the classes from the java applet package

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 31


Interface Section
• This section is used to specify an interface in Java.

• It is an optional section which is mainly used to implement multiple inheritance in Java.

• An interface is a lot similar to a class in Java but it contains only constants


and method declarations.

• To create an interface in program the interface keyword is used.

• An interface cannot be instantiated but it can be implemented by classes or extended by


other interfaces.

• Example of Interface is as follows:

interface stack{
void push(int item);
void pop();
}

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 32


Class Definition
• In this section, the class is defined which is vital part of a Java program.

• Classes are an essential part of any Java program. It defines the information about
the user-defined classes in a program.

• A class is a collection of variables and methods that operate on the fields.

• A Java program may have more than one class definition.

• Every program in Java will have at least one class with the main method.We use
the class keyword to define the class. For Example:
Class Student //Defining a Student class.
{
field;
method;
}

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 33


Main Method Class
• In this section, the main() method is defined, which is essential for all Java programs.

• The execution of all Java programs starts from the main() method, main() method is an entry point
of the class. It must be inside the class.

• Inside the main method, User can create objects and call the methods.

• To define the main() method following syntax is used:


public static void main(String args[])
{
}
• For Example:
public class Example
{
//main method declaration
public static void main(String[] args)
{
System.out.println("hello world");
}
}
19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 34
Simple Java Program
class Simple
{
public static void main(String args[])
{
System.out.println(“Welcome to d world of Java…..");
}
}
• To Save : Simple.java
• To Compile : javac Simple.java
• To Execute : java Simple.java

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 35


Parameters used in First Java Program
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is
visible to all.
static is a keyword. If we declare any method as static, it is known as the
static method. The core advantage of the static method is that there is no
need to create an object to invoke the static method. The main method is
executed by the JVM, so it doesn't require to create an object to invoke
the main method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used to print statement. Here, System is a class, out is
the object of PrintStream class, println() is the method of PrintStream
class. We will learn about the internal working of System.out.println
statement later.

19-Jan-24 Dr. Nidhi Divecha, S. K.P.I.M.C.S. 36


Java Variable:

A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables


in java:local, instance and static.

int data=50;//Here data is variable

Types of Variables

There are three types of variables

in Java:local variable

instance

variable

static

variable

class A
{
int data=50;//instance
variable static int
m=100;//static variable
void method()
{
int n=90;//local variable
}
}

Data Types in Java


Data types specify the different sizes and values that can be stored in
thevariable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include


boolean, char,byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive
data typesinclude Classes, Interfaces, and
Arrays.
Java Operator

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=


Java Keywords
Java keywords are also known as reserved words. These are predefined
words by Java so it cannot be used as a variable or object name.

Ex: implements, extends, default, public, class, static, final etc...

Java Classes/Objects
Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and
methods.

Create a Class
To create a class, use the keyword class:

Create a class named "Test" with a variable x:

public class Test {

int x = 5;

Create an Object
In Java, an object is created from a class. We have already created the class named Test,
so now we can use this to create objects.

To create an object of Test, specify the class name, followed by the object name, and use
the keyword new

Example
Create an object called "myObj" and print the value of x:

Accessing Class Members in Java


variables and methods are accessed via objects with the help of a dot (.) operator.
public class Test

int x = 5;

public static void main(String[] args) {

Test myObj = new Test(); // classname objname = new classname();

System.out.println(myObj.x); // accessing class members

Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Test:

public class Test {

int x = 5;

public static void main(String[] args) {

Test myObj1 = new Test(); // Object 1

Test myObj2 = new Test(); // Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

Method Overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

class Over

int add(int a,int b)

return a+b;
}

int add(int a,int b,int c)

return a+b+c;

class OverDemo

public static void main(String[] args)


{

Over o1 = new Over();

System.out.println("Addition is: " + o1.add(10,20));

System.out.println("Addition is : " + o1.add(10,20,30));

Java Constructors
A Java constructor is a special method which is used to initialize object. A constructor is
called automatically whenever an object is created.

It is a special method because its name and class name both are same.

It is a special type of method which is used to initialize the object.

Rules for creating Java constructor

There are two rules defined for the constructor.

 Constructor name must be the same as its class name


 A Constructor has no return type
 A Java constructor cannot be abstract, static, final.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
class Sample
{
int x,y;
Sample()
{
x=10;
y=50;
}
void display()
{
System.out.println(" X :" + x + " Y: " +y);
}
}
class SampleDemo
{
public static void main(String palak[])
{
Sample s = new Sample(); // constructor is called
s.display();
}
}

Java Parameterized Constructor


A Constructor with argument it is known as parameterized constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4
{
int id;
String name;

Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");

s1.display();
s2.display();
}
}

Constructor Overloading in Java


A class contain more than one constructor having different arguments is known as
constructor overloading.
//Java program to overload constructors
class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Constructor Vs. Member


Function(Method)
• Constructor has same name as • Member Function has different
the class itself. name.

• Constructors don’t have return • Member Functions have return


type type

• A constructor is automatically • Member Function does not


called when an object is automatically called when an
created. object is created.

• It must be placed in public • It can be placed in public,


section of class. private, protected section of
class.

19-Jan-24 Dr. Nidhi H. Divecha 14

Access Modifiers in Java


There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

JAVA API (Application Programming Interface)

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations. (input streams and
output streams used to read and write data to files )
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: awt stands for Abstract Window Toolkit Contain classes for implementing the
components for graphical user interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
Inheritance in JAVA
Inheritance is one of the key features of OOP that allows us to create a new class from an
existing class.

It is the mechanism in java by which one class is allow to inherit the features (attributes
and methods) of another class.
The new class that is created is known as subclass (child or derived class) and the
existing class from where the child class is derived is known as superclass (parent or
base class).

The extends keyword is used to perform inheritance in Java.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.

Types of Inheritance
• On the basis of class, there can be three types of inheritance in
java:

1. Single Class : Use Extends


2. Multilevel
3. Hierarchical.

• On the basis of class and interface


there can be two types of
inheritance in java:

4. Multiple Class : Use Extends


5. Hybrid Interface : Use implements

19-Jan-24 Dr. Nidhi H. Divecha 18


Note: Multiple inheritance is not supported in Java
through class.

Single Inheritance:

When Derived a new class from single base class is known as Single inheritance.

class A

void display_A()

System.out.println("A class Method");

class B extends A

void display_B()

System.out.println("B class Method");

class SingleDemo

public static void main(String args[])

B b1 = new B();

b1.display_A();

b1.display_B();

}
}

Multilevel Inheritance:

When derive a new class from already derived class is known as Multilevel
inheritance.

Hierarchical inheritance

When two or more classes inherits a single class, it is known as hierarchical


inheritance.

Command line argument:


The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be used as
an input.

They are stored as strings in the String array passed to main( ).

class CommandLineExample{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

we are printing all the arguments passed from the command-line.

class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

You might also like