JAVA - Unit 1
JAVA - Unit 1
JAVA - Unit 1
1. Introduction
1.1. Java’s Lineage
• Java is related to C++, which is a direct descendent of C. Much of the character of
Java is inherited from these two languages.
• From C, Java derives its syntax. Many of Java’s object-oriented features were
influenced by C++.
• The creation of C was a direct result of the need for a structured, efficient, high-
level language that could replace assembly code when creating systems programs.
• Invent of C++: By the early 1980s, many projects were pushing the structured
approach past its limits. To solve this problem, a new way to program was
invented, called object-oriented programming (OOP).
• Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank,
and Mike Sheridan at Sun Microsystems, Inc. in 1991.
• It took 18 months to develop the first working version.
• This language was initially called “Oak” but was renamed “Java” in 1995.
• Between the initial implementation of Oak in the fall of 1992 and the public
announcement of Java in the spring of 1995, many more people contributed to the
design and evolution of the language.
• The original impetus for Java was not the Internet! Instead, the primary motivation
was the need for a platform-independent (that is, architecture neutral) language
that could be used to create software to be embedded in various consumer
electronic devices, such as microwave ovens and remote controls.
• As you can probably guess, many different types of CPUs are used as controllers.
The trouble with C and C++ (and most other languages) is that they are designed
to be compiled for a specific target.
• Although it is possible to compile a C++ program for just about any type of CPU,
to do so requires a full C++ compiler targeted for that CPU.
• In an attempt to find such a solution, Gosling and others began work on a portable,
platform-independent language that could be used to produce code that would run
on a variety of CPUs under differing environments.
• However, with the emergence of the World Wide Web, Java was propelled to the
forefront of computer language design, because the Web, too, demanded portable
programs.
• By 1993, it became obvious to members of the Java design team that the problems
of portability frequently encountered when creating code for embedded controllers
are also found when attempting to create code for the Internet.
• This realization caused the focus of Java to switch from consumer electronics to
Internet programming.
1.2.1. Simple:
• Java is designed to be easy for the professional programmer to learn and use
effectively.
• If you are an experienced C++ programmer, moving to Java will require very
little effort.
1.2.2. Object-Oriented:
• Java supports object oriented programming paradigm
1.2.3. Robust:
• Java is robust programming language, because Java is a strictly typed
language, it checks your code at compile time. However, it also checks your
code at run time.
• Better memory management in Java compared to C/C++. In C/C++, the
programmer must manually allocate and free all dynamic memory. This
sometimes leads to problems, because programmers will either forget to free
memory that has been previously allocated or, worse, try to free some memory
that another part of their code is still using. Java virtually eliminates these
problems by managing memory allocation and deallocation for you. (In fact,
deallocation is completely automatic, because Java provides garbage
collection for unused objects.)
1.2.4. Multithreaded:
• Java was designed to meet the real-world requirement of creating interactive,
networked programs.
• Java supports multithreaded programming, which allows you to write
programs that do many things simultaneously.
1.2.5. Architecture-Neutral
• Java is designed on the principle of “write once; run anywhere, anytime,
forever.”
• It can run even if operating system upgrades, processor upgrades, and changes
in core system resources can all combine.
1.2.6. Interpreted and High Performance
• Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. This code can be interpreted
on any system that provides a Java Virtual Machine.
• Java was engineered for interpretation, the Java bytecode was carefully
designed so that it would be easy to translate directly into native machine code
for very high performance by using a just-in-time compiler.
1.2.7. Distributed
• Java is designed for the distributed environment of the Internet, because it
handles TCP/IP protocols.
• Java supports distributed computing through Remote Method Invocation
(RMI).
1.2.8. Dynamic
• Java enable dynamic link of various code block at runtime.
2
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
What is JVM ?
It is:
What it does ?
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
3
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
4
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o 2) Class(Method) Area
▪ Class(Method) Area stores per-class structures such as the
runtime constant pool, field and method data, the code for
methods.
o 3) Heap
▪ It is the runtime data area in which objects are allocated.
o 4) Stack
▪ Java Stack stores frames. It holds local variables and partial
results, and plays a part in method invocation and return.
▪ Each thread has a private JVM stack, created at the same time
as thread.
▪ A new frame is created each time a method is invoked. A frame
is destroyed when its method invocation completes.
o 5) Program Counter Register
▪ PC (program counter) register contains the address of the Java
virtual machine instruction currently being executed.
o 6) Native Method Stack
▪ It contains all the native methods used in the application.
o 7) Execution Engine
▪ A virtual processor
▪ Interpreter: Read bytecode stream then execute the
instructions.
▪ Just-In-Time(JIT) compiler: It is used to improve the
performance. JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the
amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a
Java virtual machine (JVM) to the instruction set of a specific
CPU.
o 8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface
to communicate with another application written in another language
like C, C++, Assembly etc. Java uses JNI framework to send output to
the Console or interact with OS libraries.
5
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o When we write a program in Java, firstly, the compiler compiles that program
and a bytecode is generated for that piece of code.
o After the first compilation, the bytecode generated is now run by the Java
Virtual Machine and not the processor in consideration.
o Resources required to run the bytecode are made available by the Java Virtual
Machine, which calls the processor to allocate the required resources.
• The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (Java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc) etc. to complete the development of a Java
Application.
• Some main components of JDK
o appletviewer: This tool is used to run and debug Java applets without a web
browser.
o apt: It is an annotation-processing tool.
o extcheck: it is a utility that detects JAR file conflicts.
o idlj: An IDL-to-Java compiler. This utility generates Java bindings from
a given Java IDL file.
o jabswitch: It is a Java Access Bridge. Exposes assistive technologies on
Microsoft Windows systems.
o java: The loader for Java applications. 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. The old
deployment launcher, jre, no longer comes with Sun JDK, and instead it
has been replaced by this new java loader.
o javac: It specifies the Java compiler, which converts source code into Java
bytecode.
o javadoc: The documentation generator, which automatically
generates documentation from source code comments
o jar: The specifies the archiver, which packages related class libraries
into a single JAR file. This tool also helps manage JAR files.
o javafxpackager: It is a tool to package and sign JavaFX applications.
o jarsigner: the jar signing and verification tool.
o javah: the C header and stub generator, used to write native methods.
o javap: the class file disassembler.
o javaws: the Java Web Start launcher for JNLP applications.
o JConsole: Java Monitoring and Management Console.
1.6. JRE
• What is JRE?
7
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o Java Run-time Environment (JRE) is the part of the Java Development Kit
(JDK).
o It is a freely available software distribution which has Java Class Library,
specific tools, and a stand-alone JVM.
o The source Java code gets compiled and converted to Java bytecode. If you
wish to run this bytecode on any platform, you require JRE.
o The JRE loads classes, verify access to memory, and retrieves the system
resources. JRE acts as a layer on the top of the operating system.
• What does JRE consist of?
o JRE consists of the following components:
▪ Deployment technologies such as deployment, Java plug-in, and
Java Web Start.
▪ User interface toolkits, including Abstract Window Toolkit (AWT),
Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound,
drag, and drop (DnD) and input methods.
▪ Integration libraries including Interface Definition Language
(IDL), Java Database Connectivity (JDBC), Java Naming and
Directory Interface (JNDI), Remote Method Invocation (RMI),
Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-
IIOP) and scripting.
▪ Other base libraries, including international support, input/output
(I/O), extension mechanism, Beans, Java Management Extensions
(JMX), Java Native Interface (JNI), Math, Networking, Override
Mechanism, Security, Serialization and Java for XML Processing
(XML JAXP).
▪ Lang and util base libraries, including lang and util, zip, Java
Archive (JAR), instrument, reflection, Collections, Concurrency
Utilities, management, versioning, Logging, Preferences API, Ref
Objects and Regular Expressions.
8
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o Once you write this program, you have to save it with .java extension.
Compile your program. The output of the Java compiler is a byte-code
which is platform independent.
o After compiling, the compiler generates a .class file which has the
bytecode. The bytecode is platform independent and runs on any device
having the JRE.
o From here, the work of JRE begins. To run any Java program, you need
JRE. The flow of the bytecode to run is as follows:
o Class Loader
9
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
▪ At this step, the class loader loads various classes which are
essential for running the program. The class loader dynamically
loads the classes in the Java Virtual Machine.
▪ When the JVM is started, three class loaders are used:
• Bootstrap class loader
• Extensions class loader
• System class loader
o Byte code verifier
Byte code verifier can be considered as a gatekeeper. It verifies the
bytecode so that the code doesn't make any sort of disturbance for the
interpreter. The code is allowed to be interpreted only when it passes the
tests of the Bytecode verifier which checks the format and checks for illegal
code.
o Interpreter
Once the classes get loaded and the code gets verified, then interpreter
reads the assembly code line by line and does the following two functions:
▪ Execute the Byte Code
▪ Make appropriate calls to the underlying hardware
In this way, the program runs in JRE.
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example
{
// Your program begins with a call to main().
10
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• main function
o public static void main(String args[])
▪ All Java applications begin execution by calling main( ).
▪ The public keyword is an access specifier, which allows the
programmer to control the visibility of class members. When a
class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared.
▪ main( ) must be declared as public, since it must be called by
code outside of its class when the program is started.
▪ The keyword static allows main( ) to be called without having
to instantiate a particular instance of the class. This is necessary
since main( ) is called by the Java interpreter before any objects
are made.
▪ The keyword void simply tells the compiler that main( ) does
not return a value.
• multidimensional array
o int twoD[][] = new int[4][5];
12
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
13
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
2.3. String
• String is probably the most commonly used class in Java’s class library. The
obvious reason for this is that strings are a very important part of programming.
• Every string you create is actually an object of type String.
• Even string constants are actually String objects. For example, in the statement
System.out.println("This is a String, too");
• In java, objects of type String are immutable; once a String object is created, its
contents cannot be altered. While this may seem like a serious restriction, it is
not, for two reasons:
o If you need to change a string, you can always create a new one that
contains the modifications.
o Java defines a peer class of String, called StringBuffer, which allows
strings to be altered, so all of the normal string manipulations are still
available in Java.
• Strings can be constructed a variety of ways.
o The easiest is to use a statement like this:
String myString = "this is a test";
o Java defines one operator for String objects: +. It is used to concatenate
two strings. For example, this statement,
String myString = "I" + " like " + "Java.";
14
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o The String class contains several methods that you can use.
▪ You can test two strings for equality by using equals( ).
▪ You can obtain the length of a string by calling the length( )
method.
▪ You can obtain the character at a specified index within a string
by calling charAt( ).
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
15
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• you can have arrays of strings, just like you can have arrays of any other type of
object. For example:
// Demonstrate String arrays.
class StringDemo3 {
public static void main(String args[])
{
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " + str[i]);
}
}
class HelloWorld {
System.out.println("Hello, World!");
int i;
int length = 5 ;
arr[i] = sc.nextLine();
System.out.println(arr[i]);
16
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It
provides an alternative approach to traverse the array or collection in Java.
• It is mainly used to traverse the array or collection elements.
• It is known as the for-each loop because it traverses each element one by one.
• The drawback of the enhanced for loop is that it cannot traverse the elements in
reverse order.
• Here, you do not have the option to skip any element because it does not work on
an index basis. Moreover, you cannot traverse the odd or even elements only.
• Syntax:
for(data_type variable : array | collection){
//body of for-each loop
}
• Example:
class ForEachExample1{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
18
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
class Box {
double width;
double height;
double depth;
}
o As stated, a class defines a new type of data. In this case, the new data type
is called Box. You will use this name to declare objects of type Box. It is
important to remember that a class declaration only creates a template; it
does not create an actual object. Thus, the preceding code does not cause
any objects of type Box to come into existence.
o To actually create a Box object, you will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
19
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Example:
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
20
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not
allocate any memory or copy any part of the original object. It simply makes b2
refer to the same object as does b1. Thus, any changes made to the object through
b2 will affect the object to which b1 is referring, since they are the same object.
• Adding a Method:
o Method that returns value:
class Box {
double width;
double height;
21
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
22
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
23
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
Box( )
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
o Parameterized constructor
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
• Overloading Constructors
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
class CallByValue {
26
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
27
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o Returning Objects:
▪ A method can return any type of data, including class types that you create.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
}
import java.util.Scanner;
public class array {
public int max(int [] array) {
int max = 0;
return max;
}
import java.util.Arrays;
class ReturnArrayExample1
{
public static void main(String args[])
{
int[] a=numbers(); //obtain the array
for (int i = 0; i < a.length; i++) //for loop to print the array
29
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• Static
o There will be times when you will want to define a class member that will be used
independently of any object of that class. To create such a member, precede its
declaration with the keyword static. When a member is declared static, it can be
accessed before any objects of its class are created, and without reference to any
object.
o Methods declared as static have several restrictions:
▪ They can only call other static methods.
▪ They must only access static data.
▪ They cannot refer to this or super in any way.
o static variable
o static method
As soon as the UseStatic class is loaded, all of the static statements are run. First,
a is set to 3, then the static block executes (printing a message), and finally, b is
30
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
• Introducing final
o A variable can be declared as final. Doing so prevents its contents from being
modified. This means that you must initialize a final variable when it is declared.
▪ Example of final variable
• final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
▪ Java final method
• If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
}
}
▪ Java final class
• If you make any class as final, you cannot extend it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Q) What is blank or uninitialized final variable?
Yes, but only in constructor.
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
• garbage collection:
o In some languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
32
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
o It works like this: when no references to an object exist, that object is assumed to
be no longer needed, and the memory occupied by the object can be reclaimed.
o Advantage of Garbage Collection:
▪ It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
▪ It is automatically done by the garbage collector(a part of JVM) so we don't
need to make extra efforts.
o How can an object be unreferenced?
▪ By nulling the reference
▪ By anonymous object
new Employee();
o finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:
o gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
▪ Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
▪ 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.
▪ 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.
▪ 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.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
o 1) Private: The private access modifier is accessible only within the class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
34
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
o 2) Default: If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package. It cannot be accessed from
outside the package. It provides more accessibility than private. But, it is more
restrictive than protected, and public.
package pack;
class A{
void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
//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();
35
Subject: Programming with Java (102044502)
Unit 1: Introduction, Array and String, Class Object and Method
Reference: The Complete Reference, Java 2 (Fourth Edition), Herbert Schild, -TMH
}
}
o 4) Public: The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.
//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();
}
}
36