Unit-I Java
Unit-I Java
Unit: I
Creation of Java, importance of Java to internet, byte code, Java buzzwords, data types, declaring
variables, dynamic initialization, scope and life time of variables, arrays, operators, control statements,
type conversion and casting, compiling and running of simple Java program. Concepts of classes and
objects, class fundamentals Declaring objects, assigning object reference variables, introducing
methods, constructors, usage of static with data and methods, usage of final with data, access control,
this key word, garbage collection, overloading methods and constructors, parameter passing - call by
value, recursion, nested classes and inner classes, exploring the String class.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted and Dynamic".
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
There are given the significant points that describe the history of Java.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was
so unique, most of the team members preferred Java than other names. Java is an island of Indonesia
where first coffee was produced (called java coffee). Notice that Java is just a name, not an acronym.
Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995. In 1995, Time magazine called Java one of the Ten Best Products of
1995.JDK 1.0 released in (January 23, 1996)
The reason why java has had an intense effect on the Internet is Java expands the universe of
objects that can move about freely in cyberspace. In a network, two very broad categories of objects are
transmitted between the server and your personal computer:
Passive information
For example, when you read your e-mail, you are viewing passive data. Even when you download a
program, the program‟s code is still only passive data until you execute it.
Dynamic, active programs.
A dynamic, self- executing program. Such a program is an active agent on the client computer,
yet is initiated by the server. For example, a program might be provided by the server to display
properly the data that the server is sending.
As desirable as dynamic, networked programs are, they also present serious problems in the areas
of security and portability.
1.2.1 Java Applets and Applications :
Java can be used to create two types of programs: applications and applets. An application is a
program that runs on your computer, under the operating system of that computer. When used to create
applications, java is a not much different from any other computer language.
An applet is an application designed to be transmitted over the Internet and executed by a java-
compatible Web browser. An applet is actually a tiny java program, dynamically downloaded across
the network, just like an image, sound file, or video clip. The important difference is that an applet is an
intelligent program, not just and animation or media file. In other words an applet is a program that can
react to user input and dynamically change not just run the same animation or sound over and over.
1.2.2 Security:
Prior to Java, most users did not download executable programs frequently, and those who
downloaded scan them for viruses prior to execution. When you use a Java-compatible Web browser,
you can safely download Java applets without fear of viral infection or malicious intent. Java achieves
this protection by confining a Java program to the Java execution environment and not allowing it
access to other parts of the computer.
1.2.3 Portability:
Many types of computers and operating systems are in use throughout the world - and many are
connected to the Internet. For programs to be dynamically downloaded to all the various types of
platforms connected to the Internet, some means of generating portable executable code is needed. The
same mechanism that helps ensure security also helps create portability.
Byte code is essentially the machine level language which runs on the Java Virtual Machine.
Whenever a class is loaded, it gets a stream of byte code per method of the class. Whenever that
SMVEC-Department of Information Technology Page 3
IT T45- Java Programming
method is called during the execution of a program, the byte code for that method gets invoked. Javac
not only compiles the program but also generates the byte code for the program.
It is realized that the byte code implementation makes Java a platform-independent language.
This helps to add portability to Java which is lacking in languages like C or C++. Portability ensures
that Java can be implemented on a wide array of platforms like a desktop, mobile devices, severs and
many more. Supporting this, Sun Microsystems captioned JAVA as "write once, read anywhere" or
"WORA" in significance to the byte code interpretation.
In order to print the resulting byte code in the compiled class (assuming it is in a file Test.class), we can
run the javap tool:
javap -v Test.class
And we get:
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
Simple: Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, 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.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent: Java is platform independent because it is different from other languages like
C, C++, etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. 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 a software-based
platform. The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
SMVEC-Department of Information Technology Page 5
IT T45- Java Programming
Java code can be run on multiple platforms, for example, 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 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
Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those that
are imported from network sources.
Byte code Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Portable: Java is portable because it facilitates you to carry the Java byte code to any platform. It
doesn't require any implementation.
High-performance: Java is faster than other traditional interpreted programming languages because
Java byte code 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.
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.
SMVEC-Department of Information Technology Page 6
IT T45- Java Programming
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.
Dynamic: It supports 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).
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. Java is a statically-typed programming language. It
means, all variables must be declared before its use. That is why we need to declare variable's type and
name. There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum
value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data
type.
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default
value is 0.The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.
The int data type is a 32-bit signed two's complement integer. Its value-range lies between
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum
value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default
value is 0. The long data type is used when you need a range of values more than those provided by int.
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0d.
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data
type also should never be used for precise values, such as currency.Its default value is 0.0d.
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.
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 name of reserved area allocated in memory. In other words, it is a
name of memory location.. There are three types of variables in java:
Local
Instance
Static.
1.6.2Types of Variables
Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the variable
exists. A local variable cannot be defined with "static" keyword.
Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static. It is called instance variable because its value is instance specific
and is not shared among instances.
Static variable
A variable which is declared as static is called static variable. It cannot be local. This can also
be called as the class variables. You can create a single copy of static variable and share among all
the instances of the class. Memory allocation for static variable happens only once when the class is
loaded in the memory.
Example
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
Class variables are common to all instances of a class. Instance variables are not shared between the
These variables are shared between the objects of a objects of a class. Each instance will have their
class. own copy of instance variables.
Class variables can be accessed using either class Instance variables can be accessed only through
name or object reference.( ClassName.VariableName) object reference(Objectname.VariableName).
Java allows its programmers to initialize a variable at run time also. Initializing a variable at
run time is called dynamic initialization.
Example:
public class Dynamic
{
public static void main(String[] args)
{
double dynSqrt = Math.sqrt (16);
System.out.println("sqrt of 16 is : " + dynSqrt);
}
}
OUTPUT
sqrt of 16 is : 4.0
Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is an instance
variable. General scope of an instance variable is throughout the class except in static
methods. Lifetime of an instance variable is until the object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static is known
as a class variable. General scope of a class variable is throughout the class and the lifetime of a
class variable is until the end of the program or as long as the class is loaded in memory.
SMVEC-Department of Information Technology Page 12
IT T45- Java Programming
Local Variables
All other variables which are not instance and class variables are treated as local variables including
the parameters in a method.Scope of a local variable is within the block in which it is declared and
the lifetime of a local variable is until the control leaves the block in which it is declared.
Advantages
Code Optimization: It makes the code optimized; we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
We can declare, instantiate and initialize the java array together by:
Example:
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
SMVEC-Department of Information Technology Page 14
IT T45- Java Programming
Output:
10
20
70
40
50
Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
Example:
class Testarray5
{
public static void main(String args[])
{
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
Output:
012
3456
78
In Java, an array is an object. For array object, a proxy class is created whose name can be
obtained by getClass( ).getName( ) method on the object.
Class c=arr.getClass();
String name=c.getName();
System.out.println(name);
Operators are special symbols (characters) that carry out operations on operands (variables and values)
1.8.1 Assignment Operator
Assignment operators are used in Java to assign values to variables.The assignment operator assigns the
value on its right to the variable on its left. Here, 5 is assigned to the variable age using = operator
// Assigning 5 to number1
number1 = 5;
System.out.println(number1);
Operator Meaning
- Subtraction Operator
* Multiplication Operator
/ Division Operator
% Remainder Operator
Operator Meaning
+ Unary plus (not necessary to use since numbers are positive without using it)
Operator Meaning
Output:
+number = 5.2
-number = -5.2
number = 6.2
number = 5.2
!flag = true
The equality and relational operators determines the relationship between two operands. It
checks if an operand is greater than, less than, equal to, not equal to and so on. Depending on the
relationship, it results to either true or false.
SMVEC-Department of Information Technology Page 20
IT T45- Java Programming
Operator Description
~ Bitwise Complement
^ Bitwise exclusive OR
| Bitwise inclusive OR
for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while loop
Like a while statement, except that it tests the condition at the end of the loop body.
break statement
Terminates the loop or switch statement and transfers execution to the statement immediately
following the loop or switch.
continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
Syntax
for(declaration : expression)
{
// Statements
}
Declaration − It, is of a type compatible with the elements of the array we are accessing. The
variable will be available within the for block and its value would be the same as the current
array element.
Expression − The expression can be an array variable or method call that returns an array.
Example
public class Test
{
for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String[] names ={"James","Larry","Tom","Lacy"};
Converting a value from one type to another type (data type) is known as type conversion.
Type conversion is of two types based on how the conversion is performed:
Implicit conversion (also known as automatic conversion or coercion),
Explicit conversion (also known as type casting).
Example:
class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0
Example:
class Simple
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Output:
10.5
10
We can now read in different kinds of input data that the user enters.
Here are some methods that are available through the Scanner class:
import java.util.Scanner;
import java.io.*;
class MyClass
{
public static void main(String[ ] args)
{
System.out.println(“Enter a Line”);
Scanner myVar = new Scanner(System.in);
String str1=myvar.nextLine( );
System.out.println(“Entered String is: “+str1);
}
}
Output:
Enter a line: Welcome Program
Entered String is: Welcome program
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. Thismethod can be run without creating
an instance of the class containing the main method.
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.
System.out.println() is used print statement.
A program has to be converted to a form the JVM can understand so any computer with a JVM
can interpret and run the program. Compiling a Java program means taking the programmer-readable
text in your program file (also called source code) and converting it to byte codes, which are platform-
independent instructions for the JVM.
The Java compiler is invoked at the command line on DOS shell operating systems as follows:
Note: Part of the configuration process for setting up the Java platform is setting the class path. The
class path can be set using either the -classpath option with the javac compiler command and java
interpreter command, or by setting the CLASSPATH environment variable. You need to set the class
path to point to the directory where the MyClass class is so the compiler and interpreter commands can
find it.
Once our program successfully compiles into Java bytecodes, we can interpret and run
applications on any JVM, which converts the Java byte codes to platform-dependent machine codes so
your computer can understand and run the program.The Java interpreter is invoked at the command line
on DOS shell operating systems as follows:
This runs the Java interpreter and displays the output as follows
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real
life entities.
A class is a user defined blueprint or prototype from which objects are created. It is also an
entity that determines how an object will behave and what the object will contain. It represents the set
of properties or methods that are common to all objects of one type. In general, class declarations can
include these components:
Syntax
Modifier class <class_name>
{
Data members(fields);
constructors
Methods;
}
Modifiers: A class can be public or has default access
class: Keyword used to represent the class
Class name: The name should begin with an initial letter (capitalized by convention).
Body: The class body surrounded by braces, { }.
Fields: Variables that provides the state of the class and its objects
Methods: are used to implement the behavior of the class and its objects.
Modifiers in Java:
The access modifiers in Java helps to restrict the scope of a class, constructor , variable , method
or data member.
For classes, the available modifiers are public or default (left blank), as described below:
default: A variable or method declared with no access control modifier is available to any other
class in the same package.
public: Accessible from any other class.
protected: Provides the same access as the default access modifier, with the addition that
subclasses can access protected methods and variables of the superclass (Subclasses and
superclasses are covered in upcoming lessons).
private: Accessible only within the declared class itself.
Example:
public class MyClass
{
String breed;
int age;
String color;
void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}
1.8.3 Declaring Objects in Java
An object in Java is the physical as well as logical entity whereas a class in Java is a logical
entity only. An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
SMVEC-Department of Information Technology Page 30
IT T45- Java Programming
Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.
The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory. The new operator also invokes the class constructor.
1.8.5 Accessing the instance variables (object reference variables ) and methods using objects:
Instance variables and methods are accessed via created objects. To access an instance variable,
following is the fully qualified path:
Example
class Rectangle
{
int length;
int width;
void insert(int l, int w)
{
length=l;
width=w;
}
void calculateArea( )
{
System.out.println(length*width);
}
}
class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
print( ) - is a method of java.io.PrintSteam. The print("...") prints the string inside quotation marks.
sqrt( ) - is a method of Math class. It returns square root of a number.
Modifier: Defines access type of the method i.e. from where it can be accessed in your
application.
myMethod( );
This statement calls the myMethod() method that was declared earlier.
Example:
public class MyClass
{
int age;
String breed;
String color;
String name;
void getinput( )
{
Scanner input = new Scanner (System.in);
System.out.println(“Enter the age ,breed and name”);
age=input.nextInt( );
breed=input.next( );
color=input.next( );
}
void display( )
{
System.out.println(“The Age:”+age);
System.out.println(“The Breed:”+name);
System.out.println(“The Color:”+breed);
System.out.println(“The Name:”+name);
}
void bark( )
{
System.out.println(“The Dog barks”);
}
1.10 Constructor
It is a special type of method which is used to initialize the object. It is called when an
instance of the object is created, and memory is allocated for the object. It has the same name as its
class and is syntactically similar to a method. However, constructors have no explicit return type.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero.
Syntax:
class ClassName
{
ClassName()
{
}
}
1.10.2 Types of Java constructors
There are two types of constructors in Java:
Default constructor (No-argument constructor)
Parameterized constructor
1.10.2.1 Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.It will be
invoked at the time of object creation.
Syntax :
<class_name>( ){ }
class Demo
{
int value1;
int value2;
Demo( )
{
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
Output:
101
Aravind
102
Arun
To create a static member (block, variable, method, nested class), 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.
Output:
Obj1: count is= 1
Obj2: count is= 2
Obj3: count is= 3
Static methods are the methods in Java that can be called without creating an object of class.
They are referenced by the class name itself or reference to the Object of that class.
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
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+company);
}
}
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan CTS
222 Aryan CTS
333 Sonoo CTS
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in the static block only.
Example :
class Bike
{
final int speedlimit=90; //final variable
void speed()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.speed();
}
}
Example :
public class Test
{
public final void changeName()
{
// body of method
}
}
Static Final: Attributes whose value remains same throughout all its instances , But cannot be changed
by Any instance.
Final Keyword:
Final Keyword is used to restrict the user. It means:
If you declare variable as static then you cannot change its value.
If you declare method as static then you cannot override that method.
If you make any class as final, you cannot extend it.
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
}
}
Example
A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:Hello
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.
Output:
Enter the inputs: 10 20
Sum is:30
Enter the inputs: 10 20 30
Sum is:60
Output:
Inside 1st Constructor
Value1 === 10
Value2 === 20
Inside 2nd Constructor
Value1 === 30
Value2 === 0
Inside 3rd Constructor
Value1 === 30
Value2 === 40
Arguments in Java are always passed-by-value. During method invocation, a copy of each
argument, whether its a value or reference, is created in stack memory which is then passed to the
method. In case of primitives, the value is simply copied inside stack memory which is then passed to
the callee method; in case of non-primitives, a reference in stack memory points to the actual data
which resides in the heap. When we pass an object, the reference in stack memory is copied and the
new reference is passed to the method.
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
After swapping, a = 30 and b is 45
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of the class in which it is
nested. However, reverse is not true i.e. the enclosing class does not have access to the members
of the nested class.
A nested class is also a member of its enclosing class.
As a member of its enclosing class, a nested class can be declared private, public, protected, or
package private (default).
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
Example:
class OuterClass
{
// static member
static int outer_x = 10;
int outer_y = 20;
private static int outer_private = 30;
}
}
}
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display( );
}
}
Output:
outer_x = 10
outer_private = 30
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using the
object of the outer class, following is the way in which you can instantiate the inner class.
Example:
class Outer_Demo
{
Output
String
StringBuffer
The String class implements immutable character strings, which are read-only once the string
has been created and initialized, whereas the StringBuffer class implements dynamic character strings.
if(s1.equals(obj))
{
System.out.println(“Now !! s1 and obj are Equal”);
}
else
{
System.out.println(“s1 and obj are not equal”);
}
System.out.println(“s1 + s3 =”+s1+s3);
System.out.println(“s2 + s3 =”+s2.concat(s3));
}
}
Output
s1 and s2 are Equal
s1 and obj are not Equal
Now !! s1 and obj are Equal
s1 + s3 =JavaC++
s2 + s3 =JavaC++
Method Purpose
getChars(int srcBegin, int srcEnd, Copies characters from this string into the destination character
char[ ] dst, int dstBegin) array.
indexOf(int ch) Returns the index within this string of the
first occurrence of the specified character
indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of
the specified character, starting the search at the specified
index.
lastIndexOf(int ch) Returns the index within this string of the last occurrence of
the specified character.
replace(char oldChar,char newChar) Returns a new string resulting from replacing
all occurrences of oldChar in this string
with newChar
Example:
class Example2
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“4th Character “+str.charAt(4));
System.out.println(“Index of Character U is “+str.indexOf(„U‟));
class Example3
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“String Starts with Anna : “+str.startsWith(“PU”));
System.out.println(“Ends With Anna : “+str.endsWith(“PU”));
}
}
Output :
String Starts with Anna : true
Ends With Anna : false
Output :
Substring from 6th position : University
Substring from 6th to 10th position : Univ
Method Purpose
toLowerCase() Converts all of the characters in this
String to lower case
toUpperCase() Converts all of the characters in this
String to upper case
class Example5
{
public static void main(String args[])
{
String str=”PU University”;
System.out.println(“ LowerCase “+str.toLowerCase());
System.out.println(“ UpperCase “+str.toUpperCase());
}
}
Output :
LowerCase pu university
UpperCase PU UNIVERSITY
class Example6
{
public static void main(String args[])
{
String str=”This is a test”;
int i=100;
System.out.println(“Bytes Representation “+str.getBytes());
System.out.println(“String value of integer 100 : “+String.valueOf(i));
}
}
Output :
Bytes Representation [B@10b62c9
String value of integer 100 : 100
Method Purpose
trim() This method removes white space from the front
and the end of a String.
length() Returns length of the String.
Example: finds the length of the string an eliminates white space from the front and the end of a String.
class Example7
{
public static void main(String args[])
{
String str=”JAVA “;
str=str.trim();
System.out.println(“Length of the String is “+str.length());
}
}
Output :
Length of the String is 4
1.20.10 StringBuffers:
StringBuffer class is a mutable class unlike the String class which is immutable.
Both the size and character string of a StringBuffer can be changed dynamically.
String buffers are preferred when frequent modification of character strings is involved like
appending, inserting, deleting, modifying etc.
Creation of StringBuffer:
Example:
public class StringMethods
{
public static void main(String[] args)
{
//Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer(“APPLE”);
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
//Print the Capacity of StringBuffers
System.out.println(“strBuf1 capacity : “+strBuf1.capacity());
System.out.println(“strBuf2 capacity : “+strBuf2.capacity());
System.out.println(“strBuf3 capacity : “+strBuf3.capacity());
//toString Method
System.out.println(“strBuf1 toString() is : “+strBuf1.toString());
//append Method
strBuf2.append(“HandBook”);
System.out.println(“ strBuf2 is appended with :“+strBuf2.toString());
//insert Method
strBuf2.insert(1, „A);
System.out.println(“strBuf2 when A is inserted at 1 : “+strBuf2.toString());
strBuf2.insert(2, „n);
System.out.println(“strBuf2 when n is inserted at 2 :“+strBuf2.toString());
//delete Method
strBuf2.delete(2, „n‟);
System.out.println(“strBuf2 when n is deleted at 2 :“+strBuf2.toString());
//reverse Method
strBuf2.reverse();
System.out.println(“Reversed strBuf2 : “+strBuf2);
}
}
Output :
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 toString() is : APPLE
strBuf2 is appended with :HandBook
strBuf2 when A is inserted at 1 : HAandBook
strBuf2 when n is inserted at 2 : HAnandBook
strBuf2 when n is deleted at 2 : HA
Reversed strBuf2 : AH
8.Define Methods
Functions defined inside the class definition are called as methods.
It is used to manipulate the data variables.
They can be defined only inside the appropriate classes.
It defines behavior of the object.
Syntax
[access_specifier] return_type method_name(formal_argument_list)
{
//method body
[return value]
}
9.What are different types of access modifiers (Access specifiers)?
Access specifiers are keywords that determine the type of access to the member of a class.
These keywords are for allowing privileges to parts of a program such as functions and
variables.
public: Anything declared as public can be accessed from anywhere.
private: Anything declared as private can‟t be seen outside of its class.
protected: Anything declared as protected can be accessed by classes in the same package
and subclasses in the other packages.
Syntax
Classname class-var = new classname( );
Eg
Box mybox = new Box();
more than just exception handling - it allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break.
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.
Class variables are common to all instances of a class. Instance variables are not shared between the
These variables are shared between the objects of a objects of a class. Each instance will have their
class. own copy of instance variables.
Class variables can be accessed using either class Instance variables can be accessed only through
name or object reference.( ClassName.VariableName) object reference(Objectname.VariableName).
A variable is a container which holds the value while the java program is executed. A variable is
assigned with a data type.
Local- A variable declared inside the body of the method is called local variable
Instance - A variable declared inside the class but outside the body of the method, is called
instance variable.
Java allows its programmers to initialize a variable at run time also. Initializing a variable at run
time is called dynamic initialization
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as
name. class name.
Converting a value from one type to another type (data type) is known as type conversion.
Type conversion is of two types based on how the conversion is performed:
Implicit conversion (also known as automatic conversion or coercion),
Explicit conversion (also known as type casting).
Widening
Narrowing
When a larger primitive type value is assigned in a smaller size primitive data type, this is
called narrowing of the variable. It requires explicit type-casting to required data type.
Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides
a simpler way to iterate through the elements of a collection or array.
Syntax
for(declaration : expression)
{
// Statements
}
for(int x : numbers )
{
System.out.print( x );
Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types
Arguments in Java are always passed-by-value. During method invocation, a copy of each argument,
whether its a value or reference, is created in stack memory which is then passed to the method.
38.Write about String in java?(or) What is the difference between String and StringBuffer
In Java programming language, strings are treated as objects.Handling character strings in Java
is supported through two final classes:
String
StringBuffer
The String class implements immutable character strings, which are read-only once the string
has been created and initialized, whereas the StringBuffer class implements dynamic character strings.
SMVEC-Department of Information Technology Page 73