Final JAVA PPT
Final JAVA PPT
whereas
Java is object-oriented
language.
Procedure-Oriented
Paradigm
Procedural programming means breaking
Features of Java
There is given many features of java. They are also known as java buzzwords.
1)Simple
1)Object-Oriented
2)Platform independent
3)Secured
4)Robust
5)Architecture neutral
6)Portable
7)Dynamic
8)Interpreted
9)High Performance
10)Multithreaded
11)Distributed
Simple
According to Sun, Java language is simple because: syntax is based on C++ (so
easier for programmers to learn it after C++). removed many confusing and/or
rarely-used features e.g., explicit pointers, operator overloading etc. No need to
remove unreferenced objects because there is Automatic Garbage Collection in
java.
Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behavior. Object-oriented
programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules. Basic concepts of OOPs are:
Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There
are two types of platforms software-based and hardware-based. Java provides
software-based platform. The Java platform differs from most other platforms in the
sense that it's a software-based platform that runs on top of other hardware-based
platforms.It has two components: Runtime Environment
API(Application Programming Interface)
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS
etc. 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
i.e. Write Once and Run Anywhere(WORA).
Secured
Java is secured because: No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate
access right to objects.
Security Manager- determines what resources a class can access such as
reading and writing to the local disk.
These security are provided by java language. Some security can also be
provided by application developer through SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are
lack of pointers that avoids security problem. There is automatic garbage collection
in java. There is exception handling and type checking mechanism in java. All these
points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.
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 shares the same memory. Threads are
important for multi-media, Web applications etc.
Data Abstraction
Abstraction is the process of recognizing and
focusing on important characteristics of a
situation or object and leaving/filtering out
the un-wanted characteristics of that
situation or object. Lets take a person as
example and see how that person is
abstracted in various situations
A doctor sees (abstracts) the person as patient.
name, height, weight, age, blood group, previous or
existing diseases etc
An employer sees (abstracts) a person as Employee.
name, age, health, degree of study, work experience etc
Encapsulation
Wrapping up to data and objects in a single
unit (class) is called encapsulation.
The data is not accessible to the outside
world and only those methods, which are
wrapped in the class, can access it.
These methods provide the interface
between the objects data and the program.
This insulation of the data from direct
access by the program us called data
hiding.
In Encapsulation data only performs a
specific task and is not concerned about the
internal implementation.
Inheritance
Vehicle
Racing
Car
Car
Luxurious
Car
Polymorphism
Polymorphism means the ability to take more than one
forms.
An operation may exhibit different behavior in different
instances.
Eg: Consider operation of addition. For 2 numbers the
operation will generate a sum. If the operands are string,
then the operation would produce a third string by
concatenation.
Polymorphism cont
Polymorphism is divided into 2 types:
1.
2.
Process of compilation
JDK
Java Development Kit (JDK) comes with a collection of
tools that are used for developing and running java based
programs.
The JDK is used to compile Java applications and applets.
JDK needs more Disk space as it contains JRE along with
various development tools.
It includes JRE, set of API classes, Java compiler, Web start
and additional files needed to write Java applets and
applications.
JDK
java This tool is an interpreter and can interpret
the class files generated by the javac compiler. Now
a single launcher is used for both development and
deployment.
javac the compiler, which converts source code
into Java bytecode
jar the archiver, which packages related class
libraries into a single JAR file. This tool also helps
manage JAR files.
javadoc the documentation generator, which
automatically generates documentation from
source code comments
appletviewer this tool can be used to run and
debug Java applets without a web browser.
JRE
JRE is Java Runtime Environment which is required to
run Java Applications also. JRE alone does not contains
compiler etc for Java Development.
The java programming language adds the portability by
converting the source code to byte code version which
can be interpreted by the JRE and gets converted to the
platform specific executable ones. Thus for different
platforms one has corresponding implementation of JRE.
But JRE has to meet the specification JVM (Java Virtual
Machine) Concept that serves as a link between the
Java libraries and the platform specific implementation
of JRE. Thus JVM helps in the abstraction of inner
implementation from the programmers who make use
of libraries for their programs.
JVM
JVM is machine dependent.
The use of the JVM is simple : - To change the
byte code into the machine specific code. So the
JVM converts the byte code(ie the code which we
get when we compile the .java class) into the
code that your machine/OS understands.
JVM is machine specific. So JVM for windows will
be different from JVM for Mac or Unix.
JVM is one of the most crucial part in the java
engine. It is due to JVM only that we say java
code is "Compile Once, Run Anywhere"
programming language.
JVM conti
The byte code generated when we compile the code
will be THE SAME doesn't matter we compiled the code
in Windows OS or some other. However JVM makes sure
that the byte code should be interpreted properly in the
OS under concerned so interpret the byte code
differently for different OS.
Documentation Section:
This section contains set of comments. We can write comment in java within two
ways:
1.Line comment - //
2.Block Comment - /*
*/
3.Documentation Comment is new comment in java - /** */
Package Statement:
This statement declare the package name and inform the compiler that classes
declared is contain into this package.
Ex: package student;
Import statement:
This is similar to the #include statement in the c language. It instruct to the interpreter
to load the class contained in the given package.
Ex: import student.test;
This statement instruct the interpreter to load the test class contained in the student
package.
Interface Statement:
An interface is like a class but include group of methods. Interface is a new concept
of java. This is optional and implement when we want to implement multiple
inheritance.
Class Definition:
Classes are primary and essential elements of java. Class keyword is used to declare
the class. Declare multiple classes in a java program.
Main method class
It is essential part of java program. It is starting point of java program. The main
method creates objects of various classes and establishes communication between
them. On reaching the end of main, the program terminate and the control passes
back to the operating system
Example:
/* This is sample Java program Develop By: Mr. Bhavesh Patel, Date: 17/7/2014 */
package student
import test.student
class sample
{
public static void main(String args[])
{
System.out.println(Hello world);
}
}
System.out.println("Hello World!");
Java Comments
The Java programming language supports three kinds
of comments:
1./* text */
The compiler ignores everything from /* to */.
2./** documentation */
This indicates a documentation comment (doc
comment, for short). The compiler ignores this kind of
comment, just like it ignores comments that use /* and
*/. The JDK javadoc tool uses doc comments when
preparing automatically generated documentation.
3.// text
The compiler ignores everything from // to the end of
the line.
Scanner Class:
This scanner class is used to read the data into the variable.
This class support jdk1.5 and higher version
Syntax:
Scanner sc = new Scanner (System.in)
Through this code user can get value from the keyboard.
Scanner class comes under java.util.* package so we have to import this class
from the util package.
Methods of Scanner class:
nextByte() - read byte data method is
nextLong() - read Long data method is
nextFloat() - read Float data method is
nextShort() - read short data method is
next() Reading a string, but included white space characters
nextInt() - Reading an integer data.
DataInputStream class:
This class is defined in the package java.io so we have to import it from this class.
This class support various methods to read the data from the console.
This class might throws an exception therefore we have placed the code into the try
and catch block.
Syntax:
DataInputStream input = new Data InputStream (System.in)
readLine() it is used to read string from the keyboard.
The entered value can directly be converted to an integer without storing it to the
string variable as
Integer. parseInt(input.readLine())
To convert in Long type following parser is use:
Long.pareInt (input.readLine)
Java Tokens
The smallest individual units in a program are known as
tokens.
Java language includes five types of tokens. They are:
Reserved keywords
Identifiers
Literals
Operators
Seperators
They can have alphabets, digits and the underscore and dollar
sign characters.
They must not begin with a digit.
Upper case and lower case letters are distinct.
They can be of any length.
Operators
An Operator is a symbol that takes one or more
arguments and operates on them to produce a result.
1.
2.
3.
4.
5.
6.
7.
8.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment/Decrement operators
Conditional operators
Bitwise operators
Special operators (instanceof, Dot operator)
Instanceof Operator
The instanceof is an object reference operator and
returns true if the object on the left-hand side is an
instance of the class given on the right hand side. This
operator allows us to determine whether the object
belongs to a particular class or not.
Eg: person instanceof student
It is true if the object person belongs to the class
student; otherwise it is false.
The Dot operator(.) is used to access the instance
variables and methods of class objects.
Eg: person.age
person.salary()
It is also use to access classes and sub-packages
from a packages.
Constants
Constants are the fixed value that do not change during
the execution of the program.
Variables
Variable is a identifier that denotes storage location used
to store a data value. A variable may take different values at
different times during the execution of the program.
Rules of declare a variable:
1.
2.
3.
4.
5.
6.
They can have alphabets, digits and the underscore and dollar
sign characters.
They must not begin with a digit.
Upper case and lower case letters are distinct.
It should not be a keyword.
White space is not allowed.
They can be of any length.
Datatypes
Datatypes specify the size and value that can be stored.
Declaration of variable
Declaration of variable The general form of declaration
statement is : dataype variable1, variable2;
Eg: int
count;
float finalPercentage;
double pi;
2.
Scope of Variables
The area of the program where the variable is usable
is called scope. Java variables are divided into 3
types:
1.
2.
3.
Instance variables
Class variables
Local variables
Symbolic constants
Symbolic constants are the constants that can be used
throughout the class.
They should be declared only as a class data member in
the beginning of the class.
They are written in CAPITALS to distinguish from the
normal variables.
Eg: final int PASS_MARK = 50;
final int RATE_OF_INTEREST = 8.5;
final float PI = 3.14;
Type casting
The process of converting one data type to another is
called casting.
The process of assigning a smaller type to a larger one is
known as widening or promotion and assigning larger
type to smaller one is known as narrowing.
Automatic conversion occurs when the destination type
has enough precession to store the source value.
Eg: int has enough space to hold byte value.
byte
b = 75;
int
a = b;
Category
Operator
Associativity
Postfix
()[].(dotoperator)
Lefttoright
Unary
++--!~
Righttoleft
Multiplicative
*/%
Lefttoright
Additive
+-
Lefttoright
Shift
>>>>><<
Lefttoright
Relational
>>=<<=
Lefttoright
Equality
==!=
Lefttoright
BitwiseAND
&
Lefttoright
BitwiseXOR
Lefttoright
BitwiseOR
Lefttoright
LogicalAND
&&
Lefttoright
LogicalOR
||
Lefttoright
Conditional
?:
Righttoleft
Assignment
=+=-=*=/=%=>>=<<=&=^=|=
Righttoleft
Comma
Lefttoright
DATE : 9/7/2015
GANPAT
UNIVERSITY
OBJECT ORIENTED PROGRAMMING
INTRODUCTION TO JAVA
KATHAN PATEL
publicclassCircle
{
publicdoublex,y;//centrecoordinate
publicdoubler;//radiusofthecircle
}
Adding Methods
A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
Methods are declared inside the body of the
class but immediately after the declaration
of data fields.
type MethodName (parameter-list)
The {general form of a method declaration
Method-body;
is: }
Object:
An Object in java is essentially a block of memory that contains space to store all
the instance variables.
Creating an object is also referred to as instantiating an Object
Object in java is created using new operator.
The new operator creates an object of the specified class and returns a reference
to that object.
Example:
Rectangle rect1 ;
// Declare an object
Rect1 = new Rectangle ( ) ; // instantiate the object
Both statements can be combined into one as shown below:
Rectangle rect1 = new Rectangle ();
Rectangle rect2 = new Rectangle ();
We can create any number of objects of the class.
Class RectArea
{
public static void main(String args[])
{
int area1, area2;
Rectangle rect1 = new Rectangle ();
Rectangle rect2 = new Rectangle ();
rect1.length = 15;
rect1.width = 10;
area1 = rect1.length * rect1.width;
rect2.getdata(20,12)
area2 = rect2.rectarea();
System.out.println (Area of Rect1 is: + area1);
System.out.println (Area of Rect2 is: + area2);
}
}
java Constructor:
Java constructors are the methods which are used to initialize objects.
Constructor method has the same name as that of class.
Constructors are called or invoked when an object of class is created and can't be called
explicitly.
Attributes of an object may be available when creating objects if no attribute is available
then default constructor is called.
Constructor without parameters are called default constructor.
Constructor with parameters are called parameterized constructor.
class Programming
{
//constructor method
Programming() // Default constructor
{
System.out.println("Constructor method called.");
}
public static void main(String[] args)
{
Programming object = new Programming(); //creating object
}
}
class Language
{
String name;
Language()
{
System.out.println("Constructor method called.");
}
Language(String t)
{
name = t;
}
// Parameterized constructor
void setName(String t)
{
name = t;
}
void getName()
{
System.out.println("Language name: " + name);
}
System class comes with the following two methods for garbage collection.
System.runFinalization( ): removes all objects ready of garbage collection.
System.runFinalizersOnExit(true): advice to call finalize() method before garbage
collection.
Method Overloading:
If a class have multiple methods by same name but different parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So,
we perform method overloading to figure out the program quickly.
Advantage of method overloading?
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java.
1.By changing number of arguments
2.By changing the data type
Method Overloaing is not possible by changing the return type of method because
it creates the ambiguity.
Example:
class Calculation
{
int sum(int a,int b)
{
System.out.println(a+b);
}
double sum(int a,int b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
int result=obj.sum(20,20); //Compile Time Error
}
}
Note: main () overloadin is possible.
Static keyword:
The static keyword is used in java mainly for memory management. We may apply
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
1) static variable
If you declare any variable as static, it is known static variable. The static variable can be
used to refer the common property of all objects (that is not unique for each object) e.g.
company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
2) static method
If you apply static keyword with any method, it is known as static method
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).
class Student
{
int rollno;
String name;
static String college = "ITS";
static void change()
{
college = "BBDIT";
}
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student.change();
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}//end of class
Output:Compile Time Error
2) final method
If you make any method as final, you cannot override it.
Example of final method
class Bike
{
final void run(){System.out.println("running");}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
3) final class
If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
Inheritance in JAVA:
Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent
object.
The idea behind inheritance is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new
methods and fields to adapt your new class to new situations.
Inheritance represents the IS-A relationship.
Why use Inheritance?
For Method Overriding (So Runtime Polymorphism).
For Code Reusability.
The keyword extends indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a superclass. The new class is called a
subclass.
Syntax of Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
Types of Inheritance:
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only
then we call it a single inheritance. The below flow diagram shows that class B extends only one
class which is A. Here A is a parent class of B and B would be a child class of A.
2) Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with multiple inheritance is that the derived class will have to manage the dependency on
two base classes.
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often
leads to problems in the hierarchy. This results in unwanted complexity when further extending the
class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see in
below flow diagram C is subclass or child class of B and B is a child class of A.
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C
and D inherits the same class A. A is parent class (or base class) of B,C & D.
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
method of Class A
method of Class A
method of Class A
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of Single and Multiple
inheritance. A typical flow diagram would look like below. A hybrid inheritance can be achieved in
the java in a same way as multiple inheritance can be!! Using interfaces. yes you heard it right. By
using interfaces you can have multiple as well as hybrid inheritance in Java.
Case 2: Using Interfaces: If B and C are interfaces then the above hybrid inheritance is allowed as
a single class can implement any number of interfaces in java.
class Person
{
String FirstName;
String LastName;
Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
}
class Student extends Person
{
int id;
String standard;
String instructor;
Student(String fName, String lName, int nId, String stnd, String instr)
{
super(fName,lName);
id = nId;
standard = stnd;
instructor = instr;
}
}
class SuperKeywordForConstructorDemo
{
public static void main(String args[])
{
Student sObj = new Student("Jacob","Smith",1,"1 - B","Roma");
System.out.println("Student :");
System.out.println("First Name : " + sObj.FirstName);
System.out.println("Last Name : " + sObj.LastName);
System.out.println("ID : " + sObj.id);
System.out.println("Standard : " + sObj.standard);
System.out.println("Instructor : " + sObj.instructor);
}
}
Method Override:
Method in the subclass that has the same name, same arguments and same return type as a
method in the super class. Then when the method is called, the method defined in the subclass is
invoke and executed instead of the one in the super class. This is known as method overriding.
In method overriding, if you want to call the super classs method by using the subclass object for
that super keyword is used.
Example:
public class Superclass
{
public void printMethod()
{
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass
{
public void printMethod()
{
// super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args)
{
Subclass s = new Subclass();
s.printMethod();
}
}
Output:
Printed in Superclass.
Printed in Subclass
Abstract keyword:By making a method final we ensure that the method is not redefine in a sub-class i.e.
method can never be sub classed.
Java allows us to do something that is exactly opposite to this. That is we can indicate
method must always be redefine in a sub class. Thus, making overriding compulsory.
This is done using modifier keyword abstract in the method definition.
Example:Consider geometrical shapes such as circle, rectangle and triangle.
All of them have certain common properties like area.
the common properties can be abstracted and brought under a common class.
But this method cannot have body or definition.
So, method's are define without a body or definition.
Shape
Circle
Rectang
le
Triangl
e
Java allows declaration of method without body such method's are called abstract
method's.
Abstract methods are define with a keyword abstract. A class containing at least one
abstract method is called abstract class.
Since abstract class do not have concrete methods so object for abstract classes cannot
be created.
When an abstract class is define a sub class of the abstract class must give a concrete
method.
Otherwise the sub class is also become an abstract class.
this keyword or instance variable hiding:In declaring methods and constructors parameters are used as argument the
name of parameter are generally different from that the name of instance variable however
java allows parameter and instance variable to have the same name. In order to identify
instance variables from formal System.out.println parameters the keyword "THIS" is used.
this refers to the current object.
class demothis
{
int x,y;
demothis(int x,int y)
{
this.x=x;
this.y=y;
}
}
class demotest
{
public static void main(String args[])
{
demothis d1=new demothis(20,10);
System.out.println("The value of x is" +d1.x);
System.out.println("The vlaue of y is" +d1.y);
}
}
INTERFACE:JAVA does not supports multiple inheritance that is class F extends A,B,C.
Interface are similar to abstract class but differ in their functionality. Interface is defines
method without body. Interfaces can not have instance variable but it can contain final
variable which must be initialize with values the method can have type signature the
interface helps to implement multiple inheritance in Java.
Once an interface is define another class should implement all the methods of interface.
An interface can be implement in any member of classes.
A class can implement any number of interfaces.
The general form of implementing an interface is,
class class_name [Extend super class] implements interface_A,...N)
In the implementing class methods are to be given for the abstract methods define in the
interface.
CLASS
INTERFACE
Interface
Interface keyword is used to create interface and it
cannot be used with methods.
implementation.
Whereas interface provides absolute abstraction
Abstract class can have constructors.
we can use abstract keyword to make a
class abstract. Abstract class methods can
protected, static.
declaration.
}
}
Note: A class cannot be private or protected except nested class.
2) default
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package. Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg();
//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from
outside the class only through inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:
Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println ("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
Access
Modifier
within
class
within
package
outside
package
by
subclass
only
Private
Default
or
friendly
Protected Y
Private
protected
Public
Y Access:
outside
package
This modifier makes the field visible in all subclasses of other package. But this
field is not accessible by other class in the same package
Array:
An array as a collection of variables of the same type.
Declaration:
dataType[ ]
arrayRefVar;
// preferred way.
or
dataType arrayRefVar[ ];
Example:
double[ ]
myList;
// preferred way.
Or
double
Example:
public class array_ex
{
public static void main(String []args)
{
int arrex[] = {10,20,30}; //Declaring and initializing an array of three elements
for (int i=0;i<arrex.length;i++)
{
System.out.println(arrex[i]);
}
}
}
Example:
public class array_ex
{
public static void main(String []args)
{
String strState[] = new String[3]; //declaring array of three items
strState[0] ="New York";
strState[1] ="Texas";
strState[2] ="Florida";
//Printing array
for (int i=0;i<strState.length;i++)
{
System.out.println (strState[i]) ;
}
}
}
3.4
3.5
Total is 11.7
Max is 3.5
Arrays.sort(ar);
//To sort java int array use Arrays.sort() method of java.util package.
searchVal);
/*
Output Would be
Original Array : 3 2 5 4 1
Sorted int array : 1 2 3 4 5
The index of element 4 is : 3
*/
Write the program to find two arrays are equal or not:
import java.util.Arrays;
public class Main
{
public static void main(String[] args) throws Exception
{
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary,
System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2));
}
}
Output:
Is array 1 equal to array 2??
Is array 1 equal to array 3??
true
false
ary1));
Multidimensional array :
it is used to store the data into table form or matrix form.
Declaration
int[ ][ ] num = new int[5][2];
Or
int num[ ][ ] = new int[5][2];
Create a table with fifth row and 2 column:
col [0]
Row[0]
Row[1]
Row[2]
Row[3]
Row[4]
col[1]
Initialization
num[0][0] = 1;
num[0][1] = 2;
Col [ 0 ]
num[1][0] = 5;
1
Row[0]
num[1][1] = 6;
5
num[2][0] = 11;
Row[1]
num[2][1] = 12;
11
Row[2]
num[3][0] = 15;
15
Row[3]
num[3][1] = 16;
18
num[4][0] = 18;
Row[4]
num[4][1] = 20;
Or
int[ ][ ] num={ {1,2}, {5,6}, {11,12}, {15,16}, {18,20} };
For Accessing Two Dimensional Array:
for (int i=0; i<(num.length); i++ )
{
for (int j=0;j<num[i].length;j++)
{
System.out.println(num[i][j]);
}
}
Col [ 1 ]
2
6
12
16
20
STRING
String is a sequence of character array.
In java, strings are class objects and implemented using two classes.
String
StringBuffer.
String class contain java.lang.String package.
Declaration of String:
String stringname = new String (string);
Example:
String firstname = new String (Anil) ;
String lastname = new String (Sharma) ;
In java + operator is used to concat two string.
String fullname = firstname + lastname ;
String city1 = New + Delhi ;
String Arrays:
String itemarray[ ] = new String[ 3] ;
Example:
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public class ReverseStringArrayExample
{
public static void main(String args[])
{
//String array
String[] strDays = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday"};
//first create a list from String array
List<String> list = Arrays.asList(strDays);
//next, reverse the list using Collections.reverse method
Collections.reverse(list);
//next, convert the list back to String array
strDays = (String[]) list.toArray();
String Methods:
Following table shows some string methods:
S2 = s1.toLowerCase
S2 = s1.toUpperCase
S2 = s1.replace (x , y)
S2 = s1.trim ()
S1.equals (s2)
S1.equalIgnoreCase
(s2)
S1.length ()
S1.charAt (n)
S1.compareTo (s2)
S1.concat (s2)
Concatenates s1 and s2
S1.substring ( n )
S1.substring ( n , m)
String.Valueof (p)
p.toString ()
S1.indexOf (x)
S1.indexOf (x, n)
Gives the position of x that occurs after nth position in string s1.
Example of valueOf ()
import java.io.*;
public class Test
{
public static void main(String args[])
{
double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };
System.out.println("Return Value : " + String.valueOf(d) );
System.out.println("Return Value : " + String.valueOf(b) );
System.out.println("Return Value : " + String.valueOf(l) );
System.out.println("Return Value : " + String.valueOf(arr) );
}
}
Output:
Return Value : 1.02939939939E8
Return Value : true
Return Value : 1232874
Return Value : abcdefg
Example of toString ()
import java.io.*;
public class Test
{
public static void main(String args[])
{
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :");
System.out.println(Str.toString());
}
}
Output:
Welcome to Tutorialspoint.com
Example of charAt()
public class Test
{
public static void main(String args[])
{
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
StringBuffer Class:
String class creates string of fixed length, StringBuffer class creates string of variable
length or dynamic length that can be modified in terms of content and length.
Example: We can insert characters and substring in the middle of the string or append
another string at the end of the string.
Commonly used method of StringBuffer class is as per the following:
Method
Tast
S1.setCharAt(n, x)
S1.append (s2)
S1.setLength (n)
reverse()
setLength(int
newLength)
import java.lang.*;
class stringbuffer1
{
public static void main (String args[])
{
StringBuffer str = new StringBuffer ("Object Lanaguage");
System.out.println ("Length of the string is :" + str.length());
// Inserting string in the middle
str.insert (7, "Oriented ");
System.out.println ("Modified string is " + str);
// Modifying character
str.setCharAt (6, '-');
System.out.println ("Modified string is " + str);
// Append a string at the end of string
str.append ("improves security");
System.out.println ("Modified string is " + str);
// Reverse String is
str.reverse ();
System.out.println ("Reverse string is " + str);
}
}
VECTORS:
Vector class contained in the package java.util.
Vector class can be used to create a generic dynamic array known as vector that
can hold objects of any type and any number.
Syntax:
Vector intvect = new Vector();
Vector list = new Vector (3);
In vector there is no need to define the size where as in array it is compulsory to give the
size.
Difference between array and vector:
Vector is convenient to store the object without specifying its size in array this is not
possible.
A vector can be used to store a list of objects that may be vary in size where as in array
store fixed size object.
We can add and delete object in vector but it is not possible in an array.
Task performed
list.addElement (item)
List.elementAt (10)
List.size()
List.removeElement
(item)
List.removeElementAt
(n)
List.removeAllElements()
List.copyInto (array)
List.insertElementAt
(item, n)
WRAPPER CLASS
The wrapper classes are part of the java.lang package.
primary purposes of the wrapper classes:
To provide mechanism to wrap primitive values in an object so that primitives can do activities reserved for the
objects like being added to ArrayList, Hashset, HashMap etc. collection.
The primitive data types are not objects; they do not belong to any class; they are defined in the language itself.
Sometimes, it is required to convert data types into objects in Java language. - See more at:
The following two statements illustrate the difference between a primitive data type and an object of a wrapper
class:
int x = 25;
Integer y = new Integer(33);
The first statement declares an int variable named x and initializes it with the value 25.
The second statement instantiates an Integer object.
The object is initialized with the value 33 and a reference to the object is assigned to the object variable y.
Wrapper class
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
// data types
byte grade = 2;
int marks = 50;
float price = 8.6f;
// wrapping
unwrapping