Core Java Final
Core Java Final
“Healthy citizens are the greatest asset any country can have.”
― Winston S. Churchill
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1)
2)
•
•
•
•
•
•
•
•
•
• −
• −
• −
• −
•
•
−
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
−
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Abstract class Interface
class AddTwoNumbers {
•
•
•
public class CreateObjectExample1
{
void show()
{
System.out.println("Welcome");
}
public static void main(String[] args)
{
CreateObjectExample1 obj = new
CreateObjectExample1();
obj.show();
} }
•
•
•
•
•
•
•
•
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Unit I
Chapter 1: Introduction
Contents:
History
Architecture and its Components,
Java Class File,
Java Runtime Environment,
Java Virtual Machine,
JVM Components,
The Java API,
Java Platform,
Java Development Kit,
Lambda Expressions,
Methods References,
Type Annotations,
Method Parameter Reflection,
Setting the Path Environment Variable,
Java Compiler And Interpreter,
Java Applications,
main(), public, static, void, string[] args, Statements,
White Space,
Case Sensitivity,
Identifiers,
Keywords,
Comments, braces and code blocks, variables, variable name
1. History
Java history is interesting to know. The history of java starts from Green
Team. Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc. There are given the major points that describe the
history of java.
1
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2. Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
3. Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.
Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why had they chosen java name for java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary",
"Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of
the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell
and fun to say.
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.
Java is an island of Indonesia where first coffee was produced (called java
coffee).
Notice that Java is just a name not an acronym.
Originally 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).
Java C++
Java is pure object oriented programming C++ is semi object oriented language b'coz we
language. We can't design and develop our can design and develop our programs and
programs and applications without object. applications, with and without object.
Java is Dynamic, Java allocates memory at C++ is static, C++ allocates memory at
run-time. compile-time.
Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.
2
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Java doesn't support multiple inheritance. C++ does support multiple inheritance.
Java uses interface for multiple inheritance.
Java supports automatic garbage collection. C++ does support destructors, which is
Java does not support destructors as C++ automatically invoked when the object goes
does. out of scope.
Java does not support default argument C++ does support default argument value.
value.
Java has built in support for threads. C++ has no built in support for threads.
Instead, c++ relies entirely upon the operating
system to provide this threads.
Java compiler converts source code into byte C++ generates object code and the same code
code, which is platform independent. may not run on different platforms.
There are many java versions that has been released. Current stable release of Java is
Java SE 8.
There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
3
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
Platform Independent
4
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
1. Runtime Environment
2. 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
o No explicit pointer
o Java Programs run inside virtual machine sandbox
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 are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable
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++)
5
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
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
JRE
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.
6
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
What is JVM
It is:
What it does
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Let's understand the internal architecture of JVM. It contains class loader, memory
area, execution engine etc.
7
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
1) Classloader
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.
3) Heap
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.
PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.
8
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
7) Execution Engine
It contains:
1) A virtual processor
These tasks are described in detail in the subsequent sessions. A detailed Java
architecture can be drawn as given below.
Class loader
Class loader loads all the class files required to execute the program. Class
loader makes the program secure by separating the namespace for the classes
obtained through the network from the classes available locally. Once the
bytecode is loaded successfully, then next step is bytecode verification by
bytecode verifier.
The bytecode verifier verifies the byte code to see if any security problems are
there in the code.
Once this code is verified and proven that there is no security issues with the
code, JVM will convert the byte code into machine code which will be directly
executed by the machine in which the Java program runs.
Garbage Collection
At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.
10
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Q. Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
11
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required
to be set because all the tools will be available in the current directory. But If you are
having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
1. temporary
2. permanent
To set the temporary path of JDK, you need to follow following steps:
For Example:
set path=C:\Program Files\Java\jdk1.8 \bin
12
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
For setting the permanent path of JDK, you need to follow these steps:
Copy the path c://program files//java//jdk 1.8//bin and paste in variable value.
Path Classpath
path variable is set for providing path for all classpath variable is set for provide
java tools like java, javac, javap, javah, jar, path of all java classes which is used in
appletviewer our application.
13
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Path variable is set for use all the tools like java, javac, javap, javah, jar,
appletviewer etc.
Example
"C:\Program Files\Java\jdk1.6.0\bin"
All the tools are present in bin folder so we set path upto bin folder.
14
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
5. Java API
Java compiler
Java Virtual Machine (JVM)
Java Application Programming Interface (API)
The Java API, included with the JDK, describes the function of each of its
components. In Java programming, many of these components are pre-created and
commonly used. Thus, the programmer is able to apply prewritten code via the Java
API. After referring to the available API classes and packages, the programmer easily
invokes the necessary code classes and packages for implementation.
The API is a library of available Java classes, packages and interfaces. The three API
types are as follows:
Official Java core API, which is bundled with the JDK download
Optional official Java APIs, which may be downloaded if needed
Unofficial APIs, which are third-party APIs that may be downloaded from
source websites
The APIs help programmers determine class or package functions, parameters and
other necessary information. The official API includes packages, e.g., applet
packages, graphics and GUI swing packages, input/output (IO) packages and Abstract
Windows Toolkit (AWT), among others.
There are three frames when an API starts, as follows:
The first frame shows all API components (classes and packages).
When a particular package is selected, the second frame shows all interfaces,
classes and exceptions of that particular package.
The third and primary frame provides an overview of all of API packages,
which can be expanded in the main frame to show the index, class hierarchy
and help sections.
6. Java Platform
15
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Writing in the Java programming language is the primary way to produce code
that will be deployed as byte code in a Java virtual machine (JVM); byte
code compilers are also available for other languages,
including Ada, JavaScript, Python, and Ruby.
Java eschews certain low-level constructs such as pointers and has a very
simple memory model where every object is allocated on the heap and all
variables of object types are references. Memory management is handled
through integrated automatic garbage collection performed by the JVM.
The Java platform is a suite of programs that facilitate developing and running
programs written in the Java programming language. A Java platform will
include an execution engine (called a virtual machine), a compiler and a set
of libraries; there may also be additional servers and alternative libraries that
depend on the requirements. Java is not specific to any processor or operating
system as Java platforms have been implemented for a wide variety of
hardware and operating systems with a view to enable Java programs to run
identically on all of them. Different platforms target different classes of device
and application domains:
16
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
17
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
8. Java Identifiers
All Java components require names. Names used for classes, variables, and methods
are called identifiers. In Java, there are several points to remember about identifiers.
They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
18
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
9. Lambda Expressions
Lambda expression is a new and important feature of Java which was included in Java
SE 8. It provides a clear and concise way to represent one method interface using an
expression. It is very useful in collection library. It helps to iterate, filter and extract
data from collection. Before lambda expression, anonymous inner class was the only
option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java
lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface.
Let's see a scenario. If we don't implement Java lambda expression. Here, we are
implementing an interface method without using lambda expression.
interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
Drawable d=new Drawable()
{
public void draw()
{
System.out.println("Drawing "+width);
} };
d.draw();
} }
19
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Output:
Drawing 10
Now, we are implementing the above example with the help of lambda expression.
interface Drawable
{
public void draw();
}
public class LambdaExpressionExample
{
public static void main(String[] args)
{
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
Output:
Drawing 10
Java provides a new feature called method reference in Java 8. Method reference is
used to refer method of functional interface. It is compact and easy form of lambda
expression. Each time when you are using lambda expression to just referring a
method, you can replace your lambda expression with method reference. Here, we are
explaining method reference concept in detail.
20
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
Syntax : ContainingClass::staticMethodName
Example 1
In the following example, we have defined a functional interface and referring a static
method to it's functional method say().
interface Sayable
{
void say();
}
public class MethodReference
{
public static void saySomething()
{
System.out.println("Hello, this is static method.");
}
public static void main(String[] args)
{
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
Output:
Like static methods, you can refer instance methods also. In the following example,
we are describing the process of referring the instance method.
Syntax
containingObject::instanceMethodName
21
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Example 1
In the following example, we are referring non-static methods. You can refer methods
by class object and anonymous object.
interface Sayable
{
void say();
}
public class MethodReference
{
public void saySomething()
{
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args)
{
MethodReference methodReference = new MethodReference(); // Creating object
Sayable sayable = methodReference::saySomething;
sayable.say(); // Calling interface method
Sayable sayable2 = new MethodReference()::saySomething;
sayable2.say(); // Calling interface method
}
}
Output:
3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.
Syntax: ClassName::new
Example
interface Messageable
{
Message getMessage(String msg);
}
class Message
{
public Message(String msg)
{
22
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
System.out.print(msg);
}
}
public class ConstructorReference
{
public static void main(String[] args)
{
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Output:
Hello
Java 8 has included two new features repeating and type annotations in its prior
annotations topic. In early Java versions, you can apply annotations only to
declarations. After releasing of Java SE 8 , annotations can be applied to any type use.
It means that annotations can be used anywhere you use a type. For example, if you
want to avoid NullPointerException in your code, you can declare a string variable
like this:
2. @NonNull List<String>
3. List<@NonNull String> str
4. Arrays<@NonNegative Integer> sort
5. @Encrypted File file
6. @Open Connection connection
7. void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as
input.
2 Intermediate Object Code is Generated No Intermediate Object Code
is Generated
23
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Java provides GUI development through various means like Abstract Windowing
Toolkit (AWT), Swing and JavaFX. While AWT contains a number of pre-
constructed components such as menu, button, list, and numerous third-party
components, Swing, a GUI widget toolkit, additionally provides certain advanced
components like trees, tables, scroll panes, tabbed panel and lists. JavaFX, a set of
graphics and media packages, provides Swing interoperability, 3D graphic features
and self-contained deployment model which facilitates quick scripting of Java applets
and applications.
2. Mobile Applications:
Java Platform, Micro Edition (Java ME or J2ME) is a cross-platform framework to
build applications that run across all Java supported devices, including feature phones
and smart phones. Further, applications for Android, one of the most popular mobile
operating systems, are usually scripted in Java using the Android Software
Development Kit (SDK) or other environments.
3. Embedded Systems:
Embedded systems, ranging from tiny chips to specialized computers, are components
of larger electromechanical systems performing dedicated tasks. Several devices, such
24
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
as SIM cards, blue-ray disk players, utility meters and televisions, use embedded Java
technologies. According to Oracle, 100% of Blu-ray Disc Players and 125 million
TV devices employ Java.
4. Web Applications:
Java provides support for web applications through Servlets, Struts or JSPs. The easy
programming and higher security offered by the programming language has allowed a
large number of government applications for health, social security, education and
insurance to be based on Java. Java also finds application in development of
eCommerce web applications using open-source eCommerce platforms, such as
Broadleaf.
6. Enterprise Applications:
Java Enterprise Edition (Java EE) is a popular platform that provides API and runtime
environment for scripting and running enterprise software, including network
applications and web-services. Oracle claims Java is running in 97% of enterprise
computers. The higher performance guarantee and faster computing in Java has
resulted in high frequency trading systems like Murex to be scripted in the language.
It is also the backbone for a variety of banking applications which have Java running
from front user end to back server end.
7. Scientific Applications:
Java is the choice of many software developers for writing applications involving
scientific calculations and mathematical operations. These programs are generally
considered to be fast and secure, have a higher degree of portability and low
maintenance. Applications like MATLAB use Java both for interacting user interface
and as part of the core system.
In simpler terms, a Java statement is just an instruction that explains what should
happen.
25
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
There are three main groups that encompass the different kinds of statements in Java:
//declaration statement
int number;
//expression statement
number = 4;
public static void main(String args[]) is the main method in Java. Main method
is called by JVM. Main method is called before any object creation so A
method which can called by class name it must be static so it can be called. but
here main must be public because it is accessed by outer of default
environment (call by JVM ).
When we are run java program by command =>java MY_Class
This command JVM interpret as this class must have a public static main
method. JVM search until it will not found main and if signature of main not
found then throws exception.
26
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
The method determines whether the specified char value is a white space, which
includes space, tab, or new line.
Syntax: boolean isWhitespace(char ch)
Parameters
Here is the detail of parameters −
ch − Primitive character type.
Return Value
This method returns true, if the passed character is really a white space.
Example
17. Keywords
Keywords have special meaning to the Java compiler. They help in identifying a data
type name or program construct name.
27
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about
the variable, method, class or any statement. It can also be used to hide program code
for specific time.
Syntax:
Example:
Output:
10
Example:
Output:
10
The biggest advantage to having the opening curly brace on the same line is to save
vertical space. Vertical density is an important topic when talking about easy-to-read
code, so this is definitely something that we should consider. By having the curly
brace on the same line, we reduce the (already short) code sample above by 3
lines. This means that we have more space on the screen to see additional code.
The biggest advantage to having the opening curly brace on a separate line is that the
curly braces will always line up visually (assuming that we are also using good
horizontal spacing in our code). This makes it easy to visually spot the beginning of
the code block -- we just need to find the end brace and then scan up until we see an
opening brace in the same column.
A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout
of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its
value can be changed.
29
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Example:
Types of Variable
o local variable
o instance variable
o static variable
1) Local Variables:
A variable which is declared inside the method is called local variable.
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or
block.
There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
2) Instance Variable
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
30
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
3) Static variable
A variable that is declared as static is called static variable. It cannot be local.
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
Example to understand the types of variables in java
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class
31
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Questions
1. Explain the history of Java in short. Why "Java" name was given to the
language?
2. Difference between Java and C++?
3. Explain the features of Java.
4. Difference between JDK, JRE and JVM.
5. Explain Java Virtual Machine with diagram.
6. Explain Internal Architecture of JVM.
7. Explain Java Architecture and its Components.
8. Explain compilation and running of java program. How to set path in Java?
9. Write a short note on Java API.
10. Explain the various Java Platform.
11. Explain the basic syntax and rules for Java with an example.
12. What is Java Identifiers? Explain Lambda Expressions with an example.
13. Explain Java Method References with its types.
14. What is Java Type Annotations?
15. Differentiate between Compiler and Interpreter.
16. What are the applications of Java?
17. Explain Java Statements with an example.
18. Explain the syntax of Java main().
19. Explain white spaces in Java. List various reserved keywords.
20. Define Comments. Explain the types of comments.
21. Define variables. What are the types of variables?
32
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Unit I
Chapter 1: Introduction
Contents:
History
Architecture and its Components,
Java Class File,
Java Runtime Environment,
Java Virtual Machine,
JVM Components,
The Java API,
Java Platform,
Java Development Kit,
Lambda Expressions,
Methods References,
Type Annotations,
Method Parameter Reflection,
Setting the Path Environment Variable,
Java Compiler And Interpreter,
Java Applications,
main(), public, static, void, string[] args, Statements,
White Space,
Case Sensitivity,
Identifiers,
Keywords,
Comments, braces and code blocks, variables, variable name
1. History
Java history is interesting to know. The history of java starts from Green
Team. Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc. There are given the major points that describe the
history of java.
1
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
1. James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
2. Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
3. Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.
Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why had they chosen java name for java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary",
"Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of
the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell
and fun to say.
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.
Java is an island of Indonesia where first coffee was produced (called java
coffee).
Notice that Java is just a name not an acronym.
Originally 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).
Java C++
Java is pure object oriented programming C++ is semi object oriented language b'coz we
language. We can't design and develop our can design and develop our programs and
programs and applications without object. applications, with and without object.
Java is Dynamic, Java allocates memory at C++ is static, C++ allocates memory at
run-time. compile-time.
Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.
2
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Java doesn't support multiple inheritance. C++ does support multiple inheritance.
Java uses interface for multiple inheritance.
Java supports automatic garbage collection. C++ does support destructors, which is
Java does not support destructors as C++ automatically invoked when the object goes
does. out of scope.
Java does not support default argument C++ does support default argument value.
value.
Java has built in support for threads. C++ has no built in support for threads.
Instead, c++ relies entirely upon the operating
system to provide this threads.
Java compiler converts source code into byte C++ generates object code and the same code
code, which is platform independent. may not run on different platforms.
There are many java versions that has been released. Current stable release of Java is
Java SE 8.
There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
3
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
Object-oriented
Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplify software
development and maintenance by providing some rules.
Platform Independent
4
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
1. Runtime Environment
2. 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
o No explicit pointer
o Java Programs run inside virtual machine sandbox
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 are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable
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++)
5
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
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
JRE
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.
6
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
What is JVM
It is:
What it does
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Let's understand the internal architecture of JVM. It contains class loader, memory
area, execution engine etc.
7
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
1) Classloader
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.
3) Heap
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.
PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.
8
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
7) Execution Engine
It contains:
1) A virtual processor
These tasks are described in detail in the subsequent sessions. A detailed Java
architecture can be drawn as given below.
Class loader
Class loader loads all the class files required to execute the program. Class
loader makes the program secure by separating the namespace for the classes
obtained through the network from the classes available locally. Once the
bytecode is loaded successfully, then next step is bytecode verification by
bytecode verifier.
The bytecode verifier verifies the byte code to see if any security problems are
there in the code.
Once this code is verified and proven that there is no security issues with the
code, JVM will convert the byte code into machine code which will be directly
executed by the machine in which the Java program runs.
Garbage Collection
At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.
10
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Q. Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
11
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required
to be set because all the tools will be available in the current directory. But If you are
having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
1. temporary
2. permanent
To set the temporary path of JDK, you need to follow following steps:
For Example:
set path=C:\Program Files\Java\jdk1.8 \bin
12
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
For setting the permanent path of JDK, you need to follow these steps:
Copy the path c://program files//java//jdk 1.8//bin and paste in variable value.
Path Classpath
path variable is set for providing path for all classpath variable is set for provide
java tools like java, javac, javap, javah, jar, path of all java classes which is used in
appletviewer our application.
13
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Path variable is set for use all the tools like java, javac, javap, javah, jar,
appletviewer etc.
Example
"C:\Program Files\Java\jdk1.6.0\bin"
All the tools are present in bin folder so we set path upto bin folder.
14
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
5. Java API
Java compiler
Java Virtual Machine (JVM)
Java Application Programming Interface (API)
The Java API, included with the JDK, describes the function of each of its
components. In Java programming, many of these components are pre-created and
commonly used. Thus, the programmer is able to apply prewritten code via the Java
API. After referring to the available API classes and packages, the programmer easily
invokes the necessary code classes and packages for implementation.
The API is a library of available Java classes, packages and interfaces. The three API
types are as follows:
Official Java core API, which is bundled with the JDK download
Optional official Java APIs, which may be downloaded if needed
Unofficial APIs, which are third-party APIs that may be downloaded from
source websites
The APIs help programmers determine class or package functions, parameters and
other necessary information. The official API includes packages, e.g., applet
packages, graphics and GUI swing packages, input/output (IO) packages and Abstract
Windows Toolkit (AWT), among others.
There are three frames when an API starts, as follows:
The first frame shows all API components (classes and packages).
When a particular package is selected, the second frame shows all interfaces,
classes and exceptions of that particular package.
The third and primary frame provides an overview of all of API packages,
which can be expanded in the main frame to show the index, class hierarchy
and help sections.
6. Java Platform
15
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Writing in the Java programming language is the primary way to produce code
that will be deployed as byte code in a Java virtual machine (JVM); byte
code compilers are also available for other languages,
including Ada, JavaScript, Python, and Ruby.
Java eschews certain low-level constructs such as pointers and has a very
simple memory model where every object is allocated on the heap and all
variables of object types are references. Memory management is handled
through integrated automatic garbage collection performed by the JVM.
The Java platform is a suite of programs that facilitate developing and running
programs written in the Java programming language. A Java platform will
include an execution engine (called a virtual machine), a compiler and a set
of libraries; there may also be additional servers and alternative libraries that
depend on the requirements. Java is not specific to any processor or operating
system as Java platforms have been implemented for a wide variety of
hardware and operating systems with a view to enable Java programs to run
identically on all of them. Different platforms target different classes of device
and application domains:
16
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
17
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
8. Java Identifiers
All Java components require names. Names used for classes, variables, and methods
are called identifiers. In Java, there are several points to remember about identifiers.
They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
18
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
9. Lambda Expressions
Lambda expression is a new and important feature of Java which was included in Java
SE 8. It provides a clear and concise way to represent one method interface using an
expression. It is very useful in collection library. It helps to iterate, filter and extract
data from collection. Before lambda expression, anonymous inner class was the only
option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java
lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface.
Let's see a scenario. If we don't implement Java lambda expression. Here, we are
implementing an interface method without using lambda expression.
interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
Drawable d=new Drawable()
{
public void draw()
{
System.out.println("Drawing "+width);
} };
d.draw();
} }
19
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Output:
Drawing 10
Now, we are implementing the above example with the help of lambda expression.
interface Drawable
{
public void draw();
}
public class LambdaExpressionExample
{
public static void main(String[] args)
{
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
Output:
Drawing 10
Java provides a new feature called method reference in Java 8. Method reference is
used to refer method of functional interface. It is compact and easy form of lambda
expression. Each time when you are using lambda expression to just referring a
method, you can replace your lambda expression with method reference. Here, we are
explaining method reference concept in detail.
20
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
Syntax : ContainingClass::staticMethodName
Example 1
In the following example, we have defined a functional interface and referring a static
method to it's functional method say().
interface Sayable
{
void say();
}
public class MethodReference
{
public static void saySomething()
{
System.out.println("Hello, this is static method.");
}
public static void main(String[] args)
{
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}
Output:
Like static methods, you can refer instance methods also. In the following example,
we are describing the process of referring the instance method.
Syntax
containingObject::instanceMethodName
21
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Example 1
In the following example, we are referring non-static methods. You can refer methods
by class object and anonymous object.
interface Sayable
{
void say();
}
public class MethodReference
{
public void saySomething()
{
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args)
{
MethodReference methodReference = new MethodReference(); // Creating object
Sayable sayable = methodReference::saySomething;
sayable.say(); // Calling interface method
Sayable sayable2 = new MethodReference()::saySomething;
sayable2.say(); // Calling interface method
}
}
Output:
3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.
Syntax: ClassName::new
Example
interface Messageable
{
Message getMessage(String msg);
}
class Message
{
public Message(String msg)
{
22
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
System.out.print(msg);
}
}
public class ConstructorReference
{
public static void main(String[] args)
{
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Output:
Hello
Java 8 has included two new features repeating and type annotations in its prior
annotations topic. In early Java versions, you can apply annotations only to
declarations. After releasing of Java SE 8 , annotations can be applied to any type use.
It means that annotations can be used anywhere you use a type. For example, if you
want to avoid NullPointerException in your code, you can declare a string variable
like this:
2. @NonNull List<String>
3. List<@NonNull String> str
4. Arrays<@NonNegative Integer> sort
5. @Encrypted File file
6. @Open Connection connection
7. void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as
input.
2 Intermediate Object Code is Generated No Intermediate Object Code
is Generated
23
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Java provides GUI development through various means like Abstract Windowing
Toolkit (AWT), Swing and JavaFX. While AWT contains a number of pre-
constructed components such as menu, button, list, and numerous third-party
components, Swing, a GUI widget toolkit, additionally provides certain advanced
components like trees, tables, scroll panes, tabbed panel and lists. JavaFX, a set of
graphics and media packages, provides Swing interoperability, 3D graphic features
and self-contained deployment model which facilitates quick scripting of Java applets
and applications.
2. Mobile Applications:
Java Platform, Micro Edition (Java ME or J2ME) is a cross-platform framework to
build applications that run across all Java supported devices, including feature phones
and smart phones. Further, applications for Android, one of the most popular mobile
operating systems, are usually scripted in Java using the Android Software
Development Kit (SDK) or other environments.
3. Embedded Systems:
Embedded systems, ranging from tiny chips to specialized computers, are components
of larger electromechanical systems performing dedicated tasks. Several devices, such
24
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
as SIM cards, blue-ray disk players, utility meters and televisions, use embedded Java
technologies. According to Oracle, 100% of Blu-ray Disc Players and 125 million
TV devices employ Java.
4. Web Applications:
Java provides support for web applications through Servlets, Struts or JSPs. The easy
programming and higher security offered by the programming language has allowed a
large number of government applications for health, social security, education and
insurance to be based on Java. Java also finds application in development of
eCommerce web applications using open-source eCommerce platforms, such as
Broadleaf.
6. Enterprise Applications:
Java Enterprise Edition (Java EE) is a popular platform that provides API and runtime
environment for scripting and running enterprise software, including network
applications and web-services. Oracle claims Java is running in 97% of enterprise
computers. The higher performance guarantee and faster computing in Java has
resulted in high frequency trading systems like Murex to be scripted in the language.
It is also the backbone for a variety of banking applications which have Java running
from front user end to back server end.
7. Scientific Applications:
Java is the choice of many software developers for writing applications involving
scientific calculations and mathematical operations. These programs are generally
considered to be fast and secure, have a higher degree of portability and low
maintenance. Applications like MATLAB use Java both for interacting user interface
and as part of the core system.
In simpler terms, a Java statement is just an instruction that explains what should
happen.
25
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
There are three main groups that encompass the different kinds of statements in Java:
//declaration statement
int number;
//expression statement
number = 4;
public static void main(String args[]) is the main method in Java. Main method
is called by JVM. Main method is called before any object creation so A
method which can called by class name it must be static so it can be called. but
here main must be public because it is accessed by outer of default
environment (call by JVM ).
When we are run java program by command =>java MY_Class
This command JVM interpret as this class must have a public static main
method. JVM search until it will not found main and if signature of main not
found then throws exception.
26
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
The method determines whether the specified char value is a white space, which
includes space, tab, or new line.
Syntax: boolean isWhitespace(char ch)
Parameters
Here is the detail of parameters −
ch − Primitive character type.
Return Value
This method returns true, if the passed character is really a white space.
Example
17. Keywords
Keywords have special meaning to the Java compiler. They help in identifying a data
type name or program construct name.
27
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about
the variable, method, class or any statement. It can also be used to hide program code
for specific time.
Syntax:
Example:
Output:
10
Example:
Output:
10
The biggest advantage to having the opening curly brace on the same line is to save
vertical space. Vertical density is an important topic when talking about easy-to-read
code, so this is definitely something that we should consider. By having the curly
brace on the same line, we reduce the (already short) code sample above by 3
lines. This means that we have more space on the screen to see additional code.
The biggest advantage to having the opening curly brace on a separate line is that the
curly braces will always line up visually (assuming that we are also using good
horizontal spacing in our code). This makes it easy to visually spot the beginning of
the code block -- we just need to find the end brace and then scan up until we see an
opening brace in the same column.
A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout
of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its
value can be changed.
29
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Example:
Types of Variable
o local variable
o instance variable
o static variable
1) Local Variables:
A variable which is declared inside the method is called local variable.
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or
block.
There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
2) Instance Variable
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
30
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
3) Static variable
A variable that is declared as static is called static variable. It cannot be local.
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
Example to understand the types of variables in java
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class
31
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV
Questions
1. Explain the history of Java in short. Why "Java" name was given to the
language?
2. Difference between Java and C++?
3. Explain the features of Java.
4. Difference between JDK, JRE and JVM.
5. Explain Java Virtual Machine with diagram.
6. Explain Internal Architecture of JVM.
7. Explain Java Architecture and its Components.
8. Explain compilation and running of java program. How to set path in Java?
9. Write a short note on Java API.
10. Explain the various Java Platform.
11. Explain the basic syntax and rules for Java with an example.
12. What is Java Identifiers? Explain Lambda Expressions with an example.
13. Explain Java Method References with its types.
14. What is Java Type Annotations?
15. Differentiate between Compiler and Interpreter.
16. What are the applications of Java?
17. Explain Java Statements with an example.
18. Explain the syntax of Java main().
19. Explain white spaces in Java. List various reserved keywords.
20. Define Comments. Explain the types of comments.
21. Define variables. What are the types of variables?
32
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Unit I
Chapter 2: Data Types
Contents
1. Introduction
Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals, or characters in
these variables.
Data types represent the different values to be stored in the variable. In java, there
are two types of data types:
o Primitive data types
o Non-primitive data types
33
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
It is because java uses Unicode system than ASCII code system. The \u0000 is the lowest
range of Unicode system. To get detail explanation about Unicode visit next page.
There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the eight
primitive data types in detail.
1)byte:
Byte data type is an 8-bit signed two's complement integer
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50
2)short:
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
34
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
3) int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values unless there is
a concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
4) long:
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
5) float:
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
6) double:
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values,
generally the default choice
Double data type should never be used for precise values such as currency
Default value is 0.0d
Example: double d1 = 123.4
7) boolean:
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
8) char:
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
35
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}
Output:
20
For Example
byte a = 68;
char a = 'A'
36
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well. Prefix 0 is used to indicate octal, and prefix 0x
indicates hexadecimal when using these number systems for literals.
For example
String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are −
Example
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001';
String a = "\u0001";
37
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Example:
class Rectangle
{
double length;
double breadth;
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
r1.length = 10;
r2.length = 20;
System.out.println("Value of R1's Length : " + r1.length);
System.out.println("Value of R2's Length : " + r2.length);
}}
Output:
38
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
3. Strings
Creating a String
1. String literal
2. Using new keyword
In java, Strings can be created like this: Assigning a String literal to a String instance:
39
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Each time you create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
String s1="Welcome";
String s2="Welcome"; //will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string
object with the value "Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create
new object but will return the reference to the same instance
As we saw above that when we tried to assign the same string object to two different
literals, compiler only created one object and made both of the literals to point the same
object. To overcome that approach we can create strings like this:
In this case compiler would create two different object in memory having the same string.
40
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Output:
corejava
hello
Java String Example
Here are the list of the methods available in the Java String class.
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase()); //SACHIN
System.out.println(s.toLowerCase()); //sachin
System.out.println(s); //Sachin(no change in original)
Output:
SACHIN
sachin
Sachin
The string trim() method eliminates white spaces before and after string.
Output:
Sachin
Sachin
String s="Sachin";
41
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
System.out.println(s.startsWith("Sa")); //true
System.out.println(s.endsWith("n")); //true
Output:
true
true
String s="Sachin";
System.out.println(s.charAt(0)); //S
System.out.println(s.charAt(3)); //h
Output:
S
h
String s="Sachin";
System.out.println(s.length()); //6
Output:
A pool of strings, initially empty, is maintained privately by the class String. When the
intern method is invoked, if the pool already contains a string equal to this String object
as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.
42
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Output:
Sachin
The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:
1010
The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.
Output:
4. Type Casting
Type casting in Java is used to cast one class or interface to another, if they are from
same type hierarchy.
Example:
int x = 10;
byte y = (byte)x;
43
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Widening Casting(Implicit)
Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output:
Int value 100
Long value 100
Float value 100.0
44
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Output:
Double value 100.04
Long value 100
Int value 100
Java uses primitive data types such as int, double, float etc. to hold the basic data
types for the sake of performance. Despite the performance benefits offered by the
primitive data types, there are situations when you will need an object
representation of the primitive data type. For example, many data structures in
Java operate on objects. So you cannot use primitive data types with those data
structures. To handle such type of situations, Java provides type Wrappers which
provide classes that encapsulate a primitive type within an object.
The automatic conversion of primitive data types into its equivalent Wrapper type
is known as boxing and opposite operation is known as unboxing. This is the new
feature of Java5. So java programmer doesn't need to write the conversion code.
5.1 Benefits of Autoboxing / Unboxing
Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
We don't have to perform Explicit typecasting.
45
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
It helps prevent errors, but may lead to unexpected results sometimes. Hence must
be used with care.
Auto-unboxing also allows you to mix different types of numeric objects in an
expression. When the values are unboxed, the standard type conversions can be
applied.
class BoxingExample1
{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a);//Boxing
Output: 50 5
The automatic conversion of wrapper class type into corresponding primitive type, is
known as Unboxing. Let's see the example of unboxing:
class UnboxingExample1
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);
} }
Output: 50
6. Operators
Java provides a rich set of operator’s environment. Java operators can be divided into
following categories:
46
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
6.1 Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used
in algebra.
Operator Description
% remainder of division
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0 }}
47
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Output:
15
5
50
2
0
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
> Check if operand on the left is greater than operand on the right
48
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Relational Operators
|| Logical OR (a || b) is true
49
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}}
Output:
40
80
80
240
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}}
50
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Output:
2
5
2
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value
are to be shifted. Both operands have the same precedence.
Example
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010
The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true. The bitwise & operator always checks
both conditions whether first condition is true or false.
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
51
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Output:
false
false
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c); //false && true = false
System.out.println(a); //10 because second condition is not checked
System.out.println(a<b&a++<c); //false && true = false
System.out.println(a); //11 because second condition is checked
}}
Output:
false
10
false
11
The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false. The bitwise | operator always checks both
conditions whether first condition is true or false.
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
52
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
int c=20;
System.out.println(a>b||a<c); //true || true = true
System.out.println(a>b|a<c); //true | true = true
System.out.println(a>b||a++<c); //true || true = true
System.out.println(a); //10 because second condition is not checked
System.out.println(a>b|a++<c); //true | true = true
System.out.println(a); //11 because second condition is checked
}}
Output:
true
true
true
10
true
11
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to a+=b is same
left as a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b
*= mutiply left operand with the right operand and assign the a*=b is same
result to left operand as a=a*b
/= divides left operand with the right operand and assign the a/=b is same
result to left operand as a=a/b
%= calculate modulus using two operands and assign the result a%=b is same
to left operand as a=a%b
53
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
class OperatorExample
{
public static void main(String[] args)
{
int a=10;
a+=3; //10+3
System.out.println(a);
a-=4; //13-4
System.out.println(a);
a*=2; //9*2
System.out.println(a);
a/=2; //18/2
System.out.println(a);
}}
Output:
13
9
18
9
54
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
55
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Pre-Increment Operator:
1. “++” is written before Variable name.
2. Value is Incremented First and then incremented value is used in expression.
3. “++” cannot be used over “Constant” of “final Variable“.
Syntax:
class PreIncrement
{
public static void main(String args[])
{
int num1 = 1;
int num2 = 1;
--num1;
--num2;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}}
Output:
num1 = 0
num2 = 0
56
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
class PostIncrement
{
public static void main(String args[]) {
int num1 = 1;
int num2 = 1;
num1++;
num2++;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}}
Output:
num1 = 2
num2 = 2
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}}
Output:
10
12
12
10
57
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV
Questions
58
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV
Unit 2
Chapter 1 – Control Flow Statements
Contents:
The If…Else If…Else Statement
The Switch Case Statement
1. Introduction
Decision making structures have one or more conditions to be evaluated or tested
by the program, along with a statement or statements that are to be executed if the
condition is determined to be true, and optionally, other statements to be executed
if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most
of the programming languages −
1.1 if statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true
}
59
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV
If the Boolean expression evaluates to true then the block of code inside the if
statement will be executed. If not, the first set of code after the end of the if
statement (after the closing curly brace) will be executed.
Flow Diagram
Example
if( x < 20 ) {
System.out.print("This is if statement");
}
}
}
This will produce the following result −
Output
This is if statement.
60
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV
Syntax
if(Boolean_expression)
{
// Executes when the Boolean expression is true
}
else
{
// Executes when the Boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram
Example
public class Test {
public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
Output
This is else statement
61
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV
63
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV
case value :
// Statements
break; // optional
// You can have any number of case statements.
default : // Optional
// Statements
}
The following rules apply to a switch statement −
The variable used in a switch statement can only be integers, convertable integers
(byte, short, char), strings and enums.
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.
Flow Diagram
64
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV
Example
public class Test
{
public static void main(String args[])
{
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D'
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}}
Output
Well done
Your grade is C
Questions
1. Explain if statement with its syntax, control flow diagram and example.
2. Explain if-else statement with its syntax, control flow diagram and example.
3. Explain if...else if...else statement with its syntax, control flow diagram and
example.
4. Explain Nested if-else statement with its syntax, control flow diagram and
example.
5. Explain switch statement with its syntax, control flow diagram and example.
65
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
Unit 2
Chapter 2 - Iterations
Contents:
1. Introduction:
Looping statement is the statements execute one or more statement repeatedly several
number of times. In java programming language there are three types of loops; while, for
and do-while.
66
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
In while loop first check the condition if condition is true then control goes inside the
loop body otherwise goes outside of the body. while loop will be repeats in clock wise
direction.
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}
class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(i);
i++;
}
Output
0
1
2
3
4
for loop is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements
Syntax
67
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
{
statement(s);
}
Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any
loop control variables.
Condition: This is next step after initialization step, if it is true, the body of the
loop is executed, if it is false then the body of the loop does not execute and flow
of control goes outside of the for loop.
Increment or Decrements: After completion of Initialization and Condition steps
loop body code is executed and then Increment or Decrements steps is execute.
This statement allows to update any loop control variables.
Flow Diagram
68
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
Output
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
1.3 do-while
A do-while loop is similar to a while loop, except that a do-while loop is execute
at least one time.
A do while loop is a control flow statement that executes a block of code at least
once, and then repeatedly executes the block, or not, depending on a given
condition at the end of the block (in while).
69
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
Syntax
do
{
Statement(s)
increment/decrement (++ or --)
}
while();
In below example you can see in this program i=20 and we check condition i is less than
10, that means condition is false but do..while loop execute onec and print Hello world !
at one time.
class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}}
Output
Hello world !
class dowhileDemo
{
public static void main(String args[])
70
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
{
int i=0;
do
{
System.out.println(+i);
i++;
}
while(i<5);
}
}
Output
1
2
3
4
5
71
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
Example
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
} } }
This will produce the following result −
Output
10
20
72
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
Example
public class Test
{
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
10
20
40
50
73
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
for(i=1;i<=10;i++)
{
System.out.println();
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==5)
break; //Statement 1
} } } }
Output :
12345
12345
12345
12345
12345
12345
12345
12345
12345
12345
In the above example, statement 1 will break the inner loop and jump outside from inner
loop to execute outer loop.
74
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
loop1: for(i=1;i<=10;i++)
{
System.out.println();
loop2: for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==5)
break loop1; //Statement 1
} } }}
Output :
12345
In the above example, statement 1 will break the inner loop and jump outside the outer
loop.
The for-each loop introduced in Java5. It is mainly used to traverse array or collection
elements. The advantage of for-each loop is that it eliminates the possibility of bugs and
makes the code more readable.
class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
for(int i:arr)
75
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV
{
System.out.println(i);
} } }
Output:
12
13
14
44
Questions
76
Core Java Unit 2 SYBSCIT-SEM IV
Unit II
Chapter 3 – Classes
Contents:
Types of Classes,
Scope Rules,
Access Modifier,
Instantiating Objects From A Class,
Initializing the Class Object And Its Attributes,
Class Methods,
Accessing A Method,
Method Returning A Value,
Method's Arguments,
Method Overloading,
Variable Arguments [Varargs],
Constructors,
this Instance,
Super Instance,
Characteristics of Members of A Class,
Constants,
Static fields of a class,
Static methods of a class,
Garbage Collection.
1. Introduction
class identifier
{
// class body
}
77
Core Java Unit 2 SYBSCIT-SEM IV
class Book
{
// class body
}
class A
{}
class B
{}
class C
{
public static void main(String[]args)
{
System.out.println("Application C entry point");
}}
fields
methods
78
Core Java Unit 2 SYBSCIT-SEM IV
constructors
blocks
nested class and interface
2. Scope Rules
class Scope {
public static void main(String args[])
{
int n1; // Visible in main
n1 = 10;
if(n1 == 10)
{ // start new scope
int n2 = 20; // visible only to this block
System.out.println("n1 and n2 : "+ n1 +""+ n2); // num1 and num2 both visible
here.
}
// n2 = 100; // Error! y not known here
// n1 is still visible here.
System.out.println("n1 is " + n1);
}}
Output :
n1and n2 : 10 20
n1 is 10
79
Core Java Unit 2 SYBSCIT-SEM IV
class ScopeInvalid {
public static void main(String args[]) {
int num = 1;
{ // creates a new scope
int num = 2; // Compile-time error
// num already defined
} } }
It will cause compile error because variable “num” is declared in main scope and thus it
is accessible to all the innermost blocks. However we can try this –
class ScopeInvalid
{
public static void main(String args[])
{
{ // creates a new scope
int num = 1;
}
{ // creates a new scope
int num = 2;
}}}
3. Access Modifier
Each object has members (members can be variable and methods) which can be declared
to have specific access. Java has 4 access level and 3 access modifiers. Access levels are
listed below in the least to most restrictive order.
3.1 public: Members (variables, methods, and constructors) declared public (least
restrictive) within a public class are visible to any class in the Java program, whether
these classes are in the same package or in another package. Below screen shot shows
eclipse view of public class with public members.
3.2 protected: The protected fields or methods, cannot be used for classes and Interfaces.
Fields, methods and constructors declared protected in a super-class can be accessed only
by subclasses in other packages. Classes in the same package can also access protected
fields, methods and constructors as well, even if they are not a subclass of the protected
member’s class.
3.3 Default (no value):The default access level is declared by not writing any access
modifier at all. Any class, field, method or constructor that has no declared access
modifier is accessible only by classes in the same package.
80
Core Java Unit 2 SYBSCIT-SEM IV
3.4 private: The private (most restrictive) modifiers can be used for members but cannot
be used for classes and Interfaces. Fields, methods or constructors declared private are
strictly controlled, which means they cannot be accessed by anywhere outside the
enclosing class.
Java has modifiers other than access modifiers listed below:
3.5 static: static can be used for members of a class. The static members of the class can
be accessed without creating an object of a class. Let's take an example of Vehicle class
which has run () as a static method and stop () as a non-static method. In Maruti class we
can see how to access static method run () and non-static method stop ().
3.6 final: This modifier applicable to class, method, and variables. This modifier tells the
compiler not to change the value of a variable once assigned. If applied to class, it cannot
be sub-classed. If applied to a method, the method cannot be overridden in sub-class. In
below sample, we can see compiler errors while trying to change the value of filed age
because it is defined as final while we can change the value of name field.
3.7 abstract: There are situations in which you will want to define a superclass that
declares the structure of a given abstraction without providing a complete implementation
of every method. This modifier is applicable to class and methods only.
4. Object in Java
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 intangible object is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
82
Core Java Unit 2 SYBSCIT-SEM IV
Output
Example
This example explains how to access instance variables and methods of a class.
public class Puppy
{
int puppyAge;
public Puppy(String name) // This constructor has one parameter, name.
{
System.out.println("Name chosen is :"+ name );
}
publicvoidsetAge(int age )
{
puppyAge= age;
}
publicintgetAge()
{
System.out.println("Puppy's age is :"+puppyAge);
returnpuppyAge;
}
publicstaticvoid main(String[]args)
{
PuppymyPuppy=newPuppy("tommy"); /* Object creation */
myPuppy.setAge(2); /* Call class method to set puppy's age */
myPuppy.getAge(); /* Call another class method to get puppy's age */
System.out.println("Variable Value :"+myPuppy.puppyAge); /* You can access instance
variable as follows as well */
}
}
83
Core Java Unit 2 SYBSCIT-SEM IV
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
5. Class Methods
Method definition consists of a method header and a method body. The same is shown in
the following syntax −
Syntax
modifier returnType nameofMethod (Parameter List)
{
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
84
Core Java Unit 2 SYBSCIT-SEM IV
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
Example
Here is the source code of the above defined method called min(). This method takes two
parameters num1 and num2 and returns the maximum between the two −
Example
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
public static int minFunction(int n1, int n2) /** returns the minimum of two numbers */
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This will produce the following result −
Output
Minimum value = 6
86
Core Java Unit 2 SYBSCIT-SEM IV
Output
Rank:A1
87
Core Java Unit 2 SYBSCIT-SEM IV
88
Core Java Unit 2 SYBSCIT-SEM IV
89
Core Java Unit 2 SYBSCIT-SEM IV
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by the same
name but with different parameters. The minimum number from integer and double types
is the result.
If a class inherits a method from its superclass, then there is a chance to override
the method provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the
subclass type which means a subclass can implement a parent class method based
on its requirement. In object-oriented terms, overriding means to override the
functionality of an existing method.
Example:
classAnimal
{
public void move()
{
System. out. println("Animals can move");
90
Core Java Unit 2 SYBSCIT-SEM IV
}
class Dog extends Animal
{
public void move()
{
System. out. println("Dogs can walk and run");
}
public class TestDog
{
public static void main(String args[])
{
Animal a =new Animal(); // Animal reference and object
Animal b =new Dog(); // Animal reference but Dog object
a. move(); // runs the method in Animal class
b. move(); //Runs the method in Dog class
}}
Output:
• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
• The access level cannot be more restrictive than the overridden method's access level.
For example, if the superclass method is declared public, then the overriding method in
the subclass cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.
91
Core Java Unit 2 SYBSCIT-SEM IV
• A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared
public or protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
• Constructors cannot be overridden
6. Variable Arguments
The varrags allows the method to accept zero or muliple arguments. Before
varargs either we use overloaded method or take an array as the method parameter
but it was not considered good because it leads to the maintenance problem. If we
don't know how many argument we will have to pass in the method, varargs is the
better approach.
Syntax of varargs:
class VarargsExample1
{
static void display(String... values)
{
System.out.println("display method invoked ");
}
public static void main(String args[])
{
display(); //zero argument
display("my","name","is","varargs"); //four arguments
}
}
92
Core Java Unit 2 SYBSCIT-SEM IV
Output:
class VarargsExample2
{
static void display(String... values)
{
System.out.println("display method invoked ");
for(String s:values){
System.out.println(s);
}
}
public static void main(String args[])
{
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs"); //four arguments
}
}
Output:
display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
While using the varargs, you must follow some rules otherwise program code won't
compile. The rules are as follows:
93
Core Java Unit 2 SYBSCIT-SEM IV
7. Constructors
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values
i.e. provides data for the object that is why it is known as constructor.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
94
Core Java Unit 2 SYBSCIT-SEM IV
}
public static void main(String args[]){
Bike1 b=new Bike1();
} }
Output:
Bike is created
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists.The compiler differentiates these
95
Core Java Unit 2 SYBSCIT-SEM IV
constructors by taking into account the number of parameters in the list and their
type.
class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
96
Core Java Unit 2 SYBSCIT-SEM IV
There are many differences between constructors and methods. They are given below.
There is no copy constructor in java. But, we can copy the values of one object to another
like copy constructor in C++. There are many ways to copy the values of one object into
another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s)
{
id = s.id;
97
Core Java Unit 2 SYBSCIT-SEM IV
name =s.name;
}
void display(){System.out.println(id+" "+name);
} } }
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
Output:
111 Karan
111 Karan
We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
class Student7
{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);
}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
98
Core Java Unit 2 SYBSCIT-SEM IV
Output:
111 Karan
111 Karan
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
99
Core Java Unit 2 SYBSCIT-SEM IV
In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
If local variables(formal arguments) and instance variables are different, there is no need
to use this keyword like in the following program:
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}
Output:
black
white
In the above example, Animal and Dog both classes have a common property
color. If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.
101
Core Java Unit 2 SYBSCIT-SEM IV
The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
102
Core Java Unit 2 SYBSCIT-SEM IV
In the above example Animal and Dog both classes have eat() method if we call
eat() method from Dog class, it will call the eat() method of Dog class by default
because priority is given to local.
To call the parent class method, we need to use super keyword.
The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}}
Output:
animal is created
dog is created
103
Core Java Unit 2 SYBSCIT-SEM IV
A non-static class that is created inside a class but outside a method is called
member inner class.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output:
data is 30
104
Core Java Unit 2 SYBSCIT-SEM IV
Java does not directly support constants. However, a static final variable is
effectively a constant.
The static modifier causes the variable to be available without loading an instance
of the class where it is defined. The final modifier causes the variable to be
unchangeable.
Java constants are normally declared in ALL CAPS. Words in Java constants are
normally separated by underscores.
An example of constant declaration in Java is written below:
105
Core Java Unit 2 SYBSCIT-SEM IV
static block
The static block, is a block of statement inside a Java class that will be executed when a
class is first loaded in to the JVM. A static block helps to initialize the static data
members, just like constructors help to initialize instance members in java programming
language.
class Test
{
static
{ //Code goes here
}}
Questions
106
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Unit III
Chapter 1: Inheritance
Contents:
Inheritance
Derived Class Objects
Inheritance and Access Control
Default Base Class Constructors
This and super keywords.
Abstract Classes And Interfaces
Abstract Classes
Abstract Methods
Interfaces
What Is An Interface?
How Is An Interface Different From An Abstract Class?
Multiple Inheritance
Default Implementation
Adding New Functionality
Method Implementation
Classes V/s Interfaces
Defining An Interface
Implementing Interfaces.
1. Inheritance
The mechanism of deriving the properties and methods of one class to another class
is called as inheritance.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
When you inherit from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in your current class
also.
Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
107
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
108
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class
and the new class is called child or subclass.
Following is an example demonstrating Java inheritance. In this example, you can
observe two classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.
109
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Example:
class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
110
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
3. Access Control
Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
//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.
111
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
//save by A.java
package pack;
public class A
{
public void msg()
112
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
{
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
//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[]) {
113
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Output: Hello
Single Inheritance
Multiple Inheritance (Through Interface)
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Example: Inheritence
class Employee
{
float salary=40000;
}
114
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary); // property of base class
System.out.println("Bonus of Programmer is:"+p.bonus);
} }
Single Inheritance is the simple inheritance of all, When a class extends another class(Only
one class) then we call it as Single inheritance. The below diagram represents the single
inheritance in java where Class B extends only one class Class A. Here Class B will be
the Sub class and Class A will be one and only Super class.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
115
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
} }
Example 2:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
ClassB b = new ClassB(); //Assigning ClassB object to ClassB reference
b.dispA(); //call dispA() method of ClassA
b.dispB(); //call dispB() method of ClassB
}}
Output :
disp() method of ClassA
disp() method of ClassB
116
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
In Multilevel Inheritance a derived class will be inheriting a parent class and as well as
the derived class act as the parent class to other class. As seen in the below
diagram. ClassB inherits the property of ClassA and again ClassBact as a parent
for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.
117
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Example 2:
Output:
118
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
In Hierarchical inheritance one parent class will be inherited by many sub classes. As per
the below example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will
be acting as a parent class for ClassB, ClassC and ClassD.
119
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Example 2:
120
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Output:
Example:
interface Car
{
int speed=60;
public void distanceTravelled();
}
interface Bus
{
int distance=100;
public void speed();
}
public class Vehicle implements Car,Bus
{
int distanceTravelled;
int averageSpeed;
public void distanceTravelled()
121
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
{
distanceTravelled=speed*distance;
System.out.println("Total Distance Travelled is : "+distanceTravelled);
}
public void speed()
{
int averageSpeed=distanceTravelled/speed;
System.out.println("Average Speed maintained is : "+averageSpeed);
}
public static void main(String args[])
{
Vehicle v1=new Vehicle();
v1.distanceTravelled();
v1.speed();
}
}
Output :
122
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
}
public void dispB()
{
System.out.println("disp() method of ClassB");
}}
public class ClassC extends ClassA
{
public void show()
{
System.out.println("show() method of ClassC");
}
public void dispC()
{
System.out.println("disp() method of ClassC");
}}
public class ClassD extends ClassB,ClassC
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
public static void main(String args[])
{
ClassD d = new ClassD();
d.dispD();
d.show();//Confusion happens here which show method to call
}}
Output:
Error!!
123
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Output:
In Java, we have access specifiers: private, public, protected and default. Effect of these
access specifiers are as follows:
Same class
124
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
A derived Java class does not inherit a constructor from its base class.
If a base class has a default constructor, i.e., a constructor with no arguments, then
that constructor is automatically called when a derived class is instantiated if the
derived class has its own default constructor.
A default constructor is automatically provided by the compiler.
A. this keyword
this keyword is used in the following cases:
o this can be used to refer current class instance variable.
o this can be used to invoke current class method (implicitly)
o this() can be used to invoke current class constructor.
o this can be passed as an argument in the method call.
o this can be passed as argument in the constructor call.
o this can be used to return the current class instance from the method.
125
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
B. super keyword
super keyword is used in the following cases:
o super can be used to refer immediate parent class instance variable.
o super can be used to invoke immediate parent class method.
o super() can be used to invoke immediate parent class constructor.
Example 1: super can be used to refer immediate parent class instance variable.
127
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
128
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
System.out.println("animal is created");
} }
7. Abstract Classes
A class which is declared with the abstract keyword is known as an abstract class in
Java.
It can have abstract and non-abstract methods.
It needs to be extended and its method implemented.
129
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
It cannot be instantiated.
It can have constructors and static methods.
It can have final methods which will force the subclass not to change the body of the
method.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
A method which is declared as abstract and does not have implementation is known
as an abstract method.
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as an abstract.
abstract keyword is used to declare the method as abstract.
You have to place the abstract keyword before the method name in the method
declaration.
An abstract method contains a method signature, but no method body.
Instead of curly braces, an abstract method will have a semoi colon (;) at the end.
130
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Example 2:
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw(){
System.out.println("drawing circle");
} }
//In real scenario, method is called by programmer or user
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();
s.draw();
} }
131
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Output:
drawing circle
Note: An abstract class can have data member, abstract method, method body, constructor
and even main() method.
8. Interfaces:
132
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Bank Example:
This example provides the implementation of Bank interface.
133
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
134
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
135
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV
Class Interface
1) In a class, we can only define member In an interface, we can only declare
functions, we cannot declare them. member functions, we cannot define them.
2) In a class, the data members are by In an interface, the data members are by
default non static. default final and static.
3) In a class, static member functions can In an interface, static member functions are
be defined. not allowed.
4) Objects of a class can be created Objects of an interface cannot be created
5) Constructors in a class can be defined. Constructors in an interface cannot be
defined.
6) A class cannot extend multiple classes. An interface can multiple classes.
Questions
1. Define Inheritance. Why we use inheritance? Give its syntax and terms used.
2. Explain IS-A relationship with an example. Give purpose and disadvantages of
Inheritance.
3. Explain Derived class objects in java with an example.
4. Explain the different access modifiers with an example.
5. Explain Single and Multilevel inheritance with its example.
6. Explain Hierarchical Inheritance with an example.
7. Explain Hybrid Inheritance with an example.
8. Explain Multiple Inheritance with an example.
9. Explain this and super keywords with an example.
10. Explain abstract class with its syntax and example.
11. Explain abstract method with its syntax and example.
12. Explain Interfaces in detail. How to declare interfaces? Give example.
13. How Is An Interface Different From An Abstract Class?
14. Differentiate between Classes v/s Interfaces.
136
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
UNIT III
Chapter 2: Packages
Contents
Creating Packages
Default Package
Importing Packages
Using a Package.
1. Introduction
Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
Java package provides access protection.
Java package removes naming collision.
137
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and it
is also easier to locate the related classes.
2. Creating Packages
The -d switch specifies the destination where to put the generated class file. In our case it
will create a package / folder named mypack and place the PackageDemo.class file inside
it.
You need to use fully qualified package name e.g. mypack. PackageDemo to run the
class.
138
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
2. Default Package
There are three packages that are imported by default for each source file in java.
1. package with no name
2. java.lang package
3. current package (the package in which the current file is defined)
Using package.*
If you use package.* then all the classes and interfaces inside this package will be
accessible but not subpackages.
139
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
140
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
In Java, we have access specifiers : private, public, protected and default. Effect of these
access specifiers are as follows:
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
} }
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
} }
Output:
Hello
141
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
4. Default Packages
Package Description
Name
java.lang Contains language support classes ( for e.g classes which defines primitive data types,
math operations, etc.) . This package is automatically imported.
java.io Contains classes for supporting input / output operations.
java.util Contains utility classes which implement data structures like Linked List, Hash Table,
Dictionary, etc and support for Date / Time operations.
java.applet Contains classes for creating Applets.
java.awt Contains classes for implementing the components of graphical user interface ( like
buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.
Example:
Same class
142
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV
Questions
143
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
Unit IV
Chapter 1 – Enumerations and Arrays
Contents
1. Enumerations
Example:
Natural enumerated types :
a. Planets
b. Days of week
c. Colours
d. Directions
144
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
A simple enum example where enum is declared outside any class (We have used
enum keyword instead of class keyword)
Declaration:
enumColor
{
RED, GREEN, BLUE;
}
Output: RED
Example 2: A simple enum example where Enum declaration can be done inside a
Class but not inside a Method
Java Code:
public class Test
{
enumColor
{
RED, GREEN, BLUE;
}
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}}
Output: RED
145
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
5. We can declare main() method inside enum. Hence we can invoke enum
directly from the Command Prompt.
6. A Java program to demonstrate that we can have main() inside enum class.
7. values(), ordinal() and valueOf() methods :These methods are present inside
java.lang.Enum.
a. values() method can be used to return all values present inside enum.
Order is important in enums.
b. By using ordinal() method, each enum constant index can be found,
just like array index.
c. valueOf() method returns the enum constant of the specified string
value, if exists.
import java.util.Scanner;
enum Day // An Enum class
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY;
}
public class Test // Driver class that contains an object of "day" and main().
{
Day day;
public Test(Day day) // Constructor
{
this.day = day;
}
public void dayIsLike() // Prints a line about Day using switch
{
switch (day)
{
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
} }
public static void main(String[] args) // Driver method
146
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
{
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}}
OUTPUT:
Example 2:
enumColor
{
RED, GREEN, BLUE;
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}}
numColor
{
RED, GREEN, BLUE;
}
class Test
{
public static void main(String[] args)
{
Color arr[] = Color.values(); // Calling values()
for (Color col : arr) // enum with loop
{
// Calling ordinal() to find index of color.
System.out.println(col + " at index " + col.ordinal());
}
147
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
Output:
enum and methods: enum can contain concrete methods only i.e. no any abstract
method.
Example 4: Java program to demonstrate that enums can have constructor and
concrete methods. An enum (Note enum keyword in place of class keyword)
enumColor
{
RED, GREEN, BLUE;
privateColor() // enum constructor called separately for each constant
{
System.out.println("Constructor called for : " +
this.toString());
}
public void colorInfo() // Only concrete (not abstract) methods allowed
{
System.out.println("Universal Color");
}}
public class Test
{
public static void main(String[] args) // Driver method
{
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}}
Output:
148
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
1. Enumerations are of class type, and have all the capabilities that a Java class
has.
2. Enumerations can have Constructors, instance Variables, methods and can
even implement Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit java.lang.Enum class.
2. Arrays:
149
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
o Code Optimization: It makes the code optimized, we can retrieve or sort the
data easily.
o Random access: We can get any data located at any index position.
o Size Limit: We can store only 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.
dataType[] arrayName;
Here, dataType can be a primitive data type like: int, char, Double, byte etc. or an
object arrayNameis an identifier.
Double[] data;
150
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
Note: once the length of the array is defined, it cannot be changed in the
program.
int[] age;
age = new int[5];
Here, age array can hold 5 values of type int. It's possible to define and allocate
memory of an array in one statement. You can replace two statements above with a
single statement.
You can access elements of an array by using indices. Let's consider previous
example.
151
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
classArrayExample
{
public static void main(String[] args)
{
int[] age = new int[5];
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
}}
Output:
Output:
Output:
153
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
Then,
gradeTable[ 0 ][ 1 ] // holds 42
gradeTable[ 3 ][ 4 ] // holds 93
gradeTable[ 6 ][ 2 ] // holds 78
int[][] A;
A = new int[5][7];
154
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array
for(int i=0;i<3;i++) //printing 2D array
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
} }}
Output:
123
245
445
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
155
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
{
arr[i][j] = scan.nextInt();
} }
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}}}
Output:
Note:
Two-dimensional arrays are sometimes useful, but they are much less common than
one-dimensional arrays. Java actually allows arrays of even higher dimension, but
they are only rarely encountered in practice.
156
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
We can pass the java array to method so that we can reuse the same logic on any
array. Let's see the simple example to get minimum number of an array using method.
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Output: 3
157
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
158
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
class TestArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
} }
Output: caffein
4. Vectors
Vectors (the java.util.Vector class) are commonly used instead of arrays,
because they expand automatically when new data is added to them.
The Vector class implements a growable array of objects. Like an array, it
contains components that can be accessed using an integer index. However, the
size of a Vector can grow or shrink as needed to accommodate adding and
removing items after the Vector has been created.
Each vector tries to optimize storage management by maintaining a capacity
and a capacityIncrement. The capacity is always at least as large as the vector
size; it is usually larger because as components are added to the vector, the
vector's storage increases in chunks the size of capacityIncrement. An
application can increase the capacity of a vector before inserting a large
number of components; this reduces the amount of incremental reallocation.
Java Vector Class Declaration
public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable
159
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
SN Constructor Description
1) vector() It constructs an empty vector with the default
size as 10.
2) vector(int initialCapacity) It constructs an empty vector with the
specified initial capacity and with its capacity
increment equal to zero.
3) vector(int initialCapacity, int It constructs an empty vector with the
capacityIncrement) specified initial capacity and capacity
increment.
4) Vector( Collection<? extends E> c) It constructs a vector that contains the
elements of a collection c.
Method Description
add() It is used to append the specified element in the given vector.
addAll() It is used to append all of the elements in the specified collection
to the end of this Vector.
addElement() It is used to append the specified component to the end of this
vector. It increases the vector size by one.
capacity() It is used to get the current capacity of this vector.
clear() It is used to delete all of the elements from this vector.
clone() It returns a clone of this vector.
contains() It returns true if the vector contains the specified element.
containsAll() It returns true if the vector contains all of the elements in the
specified collection.
copyInto() It is used to copy the components of the vector into the specified
array.
firstElement() It is used to get the first component of the vector.
forEach() It is used to perform the given action for each element of the
Iterable until all elements have been processed or the action
throws an exception.
indexOf() It is used to get the index of the first occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.
insertElementAt() It is used to insert the specified object as a component in the
given vector at the specified index.
160
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
lastIndexOf() It is used to get the index of the last occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.
remove() It is used to remove the specified element from the vector. If the
vector does not contain the element, it is unchanged.
removeAll() It is used to delete all the elements from the vector that are
present in the specified collection.
replaceAll() It is used to replace each element of the list with the result of
applying the operator to that element.
setSize() It is used to set the size of the given vector.
sort() It is used to sort the list according to the order induced by the
specified Comparator.
import java.util.*;
class VectorExample
{
public static void main(String args[])
{
Vector<String> vec = new Vector<String>(4);
vec.add("Sunday"); //Adding elements to a vector
vec.add("Monday");
vec.add("Tuesday");
vec.add("Wednesday");
System.out.println("Size is: "+vec.size()); //Check size and capacity
System.out.println("Default capacity is: "+vec.capacity());
System.out.println("Vector element is: "+vec); //Display Vector elements
vec.addElement("Thursday");
vec.addElement("Friday");
vec.addElement("Saurday");
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
161
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
162
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
The java.util.vector.size() method in Java is used to get the size of the Vector or the
number of elements present in the Vector.
1. Syntax:
Vector.size()
2. Parameters: The method does not take any parameter.
3. Return Value: The method returns the size or the number of elements present
in the Vector.
4. Below programs illustrate the Java.util.Vector.size() method:
import java.util.Vector;
class VectorDemo
{
public static void main(String[] args)
{
Vector<Integer> vec = new Vector<Integer>(4);
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
System.out.println("Size of the vector: "+vec.size());
} }
Output:
import java.util.Vector;
public class VectorDemo
{
public static void main(String[] args) {
Vector vec = new Vector(4);
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(3);
System.out.println("Index of 3 is :"+vec.indexOf(3)); // let us get the index of 3
} }
163
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV
Output:
Index of 3 is: 1
Questions
Enumeration:
1. What is enumeration in Java? Explain with suitable example.
2. What are the objectives of using Enumeration in Java?
3. With a Java program explain how to define and use an enumeration.
4. Explain how enum can be declared inside a class but not inside a method?
5. What is the importance or significance of enum for a Java programmer?
6. With the help of a Java program explain working on enum by using switch
7. Explain how values(),ordinal() and valueOf() methods can be used through enum
8. Can enum have constructor and concrete methods? if yes explain with suitable Java
Program
Array:
1. What is an Array in Java? Explain its properties as accepted by Java Complier
2. What are the Advantages and disadvantages of using Array in Java?
3. With suitable Java program explain how to declare and index an array
4. How many elements can an array hold explain in detail?
5. How to access the elements through Array index?
6. Write program to explain how to declare, instantiate, initialize and traverse the Java Array
7. What are various types of Arrays in Java? Explain with suitable example
8. Write a detailed note on Two dimensional Arrays in Java
9. Explain the structure of 2 dimensional array in Java
10. How to work with 2D array in Java?
11. Write a simple java program to explain 2D array in java, take input from user.
12. What are multi-dimensional arrays in Java explain with suitable example?
13. How to pass Array to a method in Java?
14. How to process Array elements? Explain with example
15. Explain the various ways available to copy array in Java
Vector:
1. What are vectors in Java? Explain the characteristics or features of vector in Java
2. What are the various ways of doing Java vector class declaration
3. Explain the four constructors of Vector in Java
4. Explain 5 methods used in Java Vector Class
5. What are the method to access the empty and last elements in Java vectors
6. Explain the functions of following methods: removeAll(), replaceAll(),
setSize(),size(),sort()
7. How to add elements to a Vector in Java
8. Write a program to explain how to search for elements in a vector
9. What are ways through which you can check the size of the Vector in Java?
164
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV
Unit IV
Chapter 2-Multithreading
Contents
1. Threading
165
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV
Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.
Modifier and
S.N. Method Description
Type
1) void start() It is used to start the execution of the
thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount
of time.
4) static Thread currentThread() It returns a reference to the currently
executing thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread
object to pause and allow other threads to
execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and
all of its subgroups.
166
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV
Class constructors
A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state. But for better understanding the threads, we are explaining it in the 5
states. The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
167
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
1. A new thread starts(with new callstack).
2. The thread moves from New state to the Runnable state.
3. When the thread gets a chance to execute, its target run() method will run.
Output:
If you are not extending the Thread class, your class object would not be treated as
a thread object. So you need to explicitly create Thread class object. We are
169
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV
passing the object of your class that implements Runnable so that your class run()
method may execute.
Questions
170