Java UnitI Ppt
Java UnitI Ppt
403)
2nd year- 4th Sem (IT1 and IT2),
Monalisa Panigrahi
Topics (Syllabus)
Introduction: Why Java, History of Java, JVM, JRE, Java
Environment, Java Source File Structure, and Compilation.
Fundamental,
Programming Structures in Java: Defining Classes in Java,
Constructors, Methods, Access Specifies, Static Members, Final
Members, Comments, Data types, Variables, Operators, Control
Flow, Arrays & String.
Object Oriented Programming: Class, Object, Inheritance Super
Class, Sub Class, Overriding, Overloading, Encapsulation,
Polymorphism, Abstraction, Interfaces, and Abstract Class.
Packages: Defining Package, CLASSPATH Setting for Packages,
Making JAR Files for Library Packages, Import and Static Import
Naming Convention For Packages
Introduction to JAVA
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.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is
called enterprise application. It has advantages of the 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.
Java is an Object Oriented
language
1.Abstraction
2.Encapsulation
3.Inheritance
4.Polymorphism
Object-Oriented Programming is a
methodology or paradigm to design a
program using classes and objects.
Object means a real-world entity such as a pen, chair,
table, computer, watch, etc. An Object can be defined as
an instance of a class. An object contains an address and
takes up some space in memory. Objects can
communicate without knowing the details of each other's
data or code.
Class: Collection of objects is called class. It is a logical entity. A class can also be
defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
Inheritance: When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.
Encapsulation: Binding (or wrapping) code and data together into a single unit are
known as encapsulation. For example, a capsule, it is wrapped with different
medicines. A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
What is the difference
between an object-oriented
programming language and
object-based programming
language?
Object-based programming language
follows all the features of OOPs except
Inheritance. JavaScript and VBScript are
examples of object-based programming
languages.
C++ vs Java
Comparison Index C++ Java
Platform-independent C++ is platform-dependent. Java is platform-independent.
Mainly used for C++ is mainly used for system Java is mainly used for application programming. It is widely used in window,
programming. web-based, enterprise and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpreter for printing systems but
applications programming. It was an later extended as a support network computing. It was designed with a goal
extension of of being easy to use and accessible to a broader audience.
C programming language.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved
by interfaces in java.
Operator Overloading C++ supports operator overloading. Java doesn't support operator overloading.
Pointers C++ supports pointers. You can Java supports pointer internally. However, you can't write the pointer
write pointer program in C++. program in java. It means java has restricted pointer support in java.
Compiler and Interpreter C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java source code is converted into
compiled and run using the compiler bytecode at compilation time. The interpreter executes this bytecode at
which converts source code into runtime and produces output. Java is interpreted that is why it is platform
machine code so, C++ is platform independent.
dependent.
Call by Value and Call by C++ supports both call by value and call by Java supports call by value only. There is no
reference reference. call by reference in java.
Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.
Thread Support C++ doesn't have built-in support for threads. It Java has built-in thread support.
relies on third-party libraries for thread support.
Documentation comment C++ doesn't support documentation comment. Java supports documentation comment (/** ...
*/) to create documentation for java source
code.
Virtual Keyword C++ supports virtual keyword so that we can decide Java has no virtual keyword. We can override
whether or not override a function. all non-static methods by default. In other
words, non-static methods are virtual by
default.
unsigned right shift >>> C++ doesn't support >>> operator. Java supports unsigned right shift >>>
operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.
Inheritance Tree C++ creates a new inheritance tree always. Java uses a single inheritance tree always
because all classes are the child of Object class
in java. The object class is the root of the
inheritance tree in java.
All Java components require names. Names used for classes, variables, and
methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as
follows −
All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
}
}
Output: 22
21
Arithmetic operator
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output: 21
Type Casting in Java
If Statement:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
} } }
Output: Age is greater than 18
If-else statement
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Output: 2
11
45
9
Enhanced For loop
Enhanced for loop is useful when you want to iterate
Array/Collections, it is easy to write and understand.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
Outpu
}
t: 2
11
45
9
Practice for loop
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
Output :10
}while(i>1); 9
8
}
7
} 6
5
4
3
2
Continue Statement
Continue statement is mostly used inside loops. Whenever it is
encountered inside a loop, control directly jumps to the beginning of
the loop for next iteration, skipping the execution of statements inside
loop’s body for the current iteration. This is particularly useful when
you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that
particular iteration.
public class ContinueExample {
public static void main(String args[]){
for (int j=0; j<=6; j++) {
if (j==4)
{
continue;
}
System.out.print(j+" "); } } }
Output: 0 1 2 3 5 6
public class MyClass { // Class declaration
// Constructor
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
// Methods
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Object and class example
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{ Classname objname = new constructor
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
Output: 0
} null
}
main outside the class
1. By reference variable
2. By method
3. By constructor
By reference variable
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Balagurusamy";
System.out.println(s1.id+" "+s1.name);//printing members with a white
space
} Output: 101 Balagurusamy
}
By method
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n; }
void displayInformation(){System.out.println(rollno+" "+name); } }
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan"); Output: 111 Karan
s1.displayInformation(); 222 Aryan
s2.displayInformation(); } }
Constructor
}
}
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
class Student4{
int id;
String name;
id = i;
name = n; }
s1.display();
s2.display(); } }
Copy Constructor
2. Multidimensional Array
Creating an array
Creation of an array involves three steps:
type var-name[];
OR
type[] var-name;
arrayname=new type[size];
It assigns the reference of the newly created array to the variable array name
279
361
742
Passing Arrays to Methods
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr); }
public static void sum(int[] arr) {
// getting sum of array values
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum); } }
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint”
There are two ways to create String object:
By string literal: String s="welcome";
By new keyword: String s=new String("Welcome")
Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new
keyword
System.out.println(s1);
System.out.println(s2);
Output: java
System.out.println(s3); strings
}} example
No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.
10 boolean equals(Object another) checks the equality of string with the given object.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.
28 static String valueOf(int value) converts given type into string. It is an overloaded method.
What is a class?
A class consists of
a collection of fields, or variables, very much like the
named fields of a struct
all the operations (called methods) that can be
performed on those fields
can be instantiated
A class describes objects and operations defined
on those objects
Name conventions
class Person {
String name;
int age;
void birthday ( ) {
System.out.println (name + ' is
now ' + age);
}
}
Creating and using an
object
Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
Object and class Example
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example:
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}
public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics"; Output: Beginnersbook
public static void main(String args[]){
Teacher
Physics
PhysicsTeacher obj = new PhysicsTeacher();
Teaching
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
Types of inheritance in
java
On the basis of class, there can be three types of
inheritance in java: single, multilevel and
hierarchical.
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output: weeping...
barking...
eating...
Hierarchical Inheritance
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{ Output: meowing...
public static void main(String args[]){ eating...
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Encapsulation
Encapsulation in Java is a process of wrapping code and
data together into a single unit, for example, a capsule
which is mixed of several medicines.
int Roll;
String Name;
double Marks;
Roll = R;
Name = N;
Marks = M; }
Roll = R;
Name = N;
Marks = M; }
void Display() {
class ConstructorOverloadingDemo {
S1.Display();
1 Kumar 78.53
2 Sumit 89.42
S2.Display(); } }
role of this () in
constructor overloading
public class OverloadingExample2{
OverloadingExample2() {
rollNum =100; }
OverloadingExample2(int rnum) {
*/
return rollNum; }
this.rollNum = rollNum; }
System.out.println(obj.getRollNum()); } }
Output: 112
this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword: Here is given the 6 usage of java this keyword.
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance
of a class.
A static method can access static data member and can change the value
of it.
Example of static method
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x; } Output: 125
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result); } }
Java static block
//Overridden method
//Overriding method
// When Parent class reference refers to the parent class object then in this case overridden method (the method of
parent class) is called. //
obj.disp();
/* When parent class reference refers to the child class object then the overriding method (method of child class) is
called.
obj2.disp(); } }
Output: disp() method of parent class
disp() method of Child class
Super
keyword
The super keyword is used for calling the parent class method/constructor.
super.myMethod() calls the myMethod() method of base class while super() calls
the constructor of base class.
class ABC{
public void myMethod()
{
System.out.println("Overridden method");
} }
class Demo extends ABC{
public void myMethod(){
//This will call the myMethod() of parent class
super.myMethod();
System.out.println("Overriding method"); }
public static void main( String args[]) {
Demo obj = new Demo();
obj.myMethod(); } }
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static Interface has only static and final variables.
variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement An interface can extend another Java interface only.
multiple Java interfaces.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".
8) A Java abstract class can have class members like private, Members of a Java interface are public by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Packages
A java package is a group of similar types of
classes, interfaces and sub-packages
Package in java can be categorized in two form,
built-in package and user-defined package.
There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Advantages of using a
package in Java
Reusability
Better Organization
Name Conflicts
Types of packages in Java
As mentioned in the beginning of this guide that we have two types of packages in
java.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc
are known as built-in packages.
Example of package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
Syntax: javac -d directory javafilename
Ex: javac -d . Simple.java
To Run: java mypack.Simple
How to access package
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using
packagename.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Using fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
How to send the class file to another
directory or drive
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run: To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
e:\sources> java -classpath c:\classes mypack.Simple
How to put two public classes
in a package
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
Sub packages in Java
A package inside another package is known as sub package. For example If I
create a package inside letmecalculate package then that will be called sub
package.
Lets say I have created another package inside letmecalculate and the sub
package name is multiply. So if I create a class in this subpackage it should have
this package declaration in the beginning:
Syntax: package letmecalculate.multiply;
Multiplication.java
package letmecalculate.multiply;
public class Multiplication {
int product(int a, int b){
return a*b;} }
Now if I need to use this Multiplication class I have to either import the package like
this:
import letmecalculate.multiply;
or I can use fully qualified name like this:
letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();
Static import