Core Java Unit 1
Core Java Unit 1
BCA SEM - VI
Unit - 1
1
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
TOPIC – 1
History of java, Features of Java, Applications of Java, Java Virtual Machine (JVM)
and Byte Code, Buzzwords.
Introduction to java
Java is a blend of the best elements of its rich heritage combined with the innovative concepts
required by its unique mission.
Java has become inseparably linked with the online environment of the Internet
Computer language innovation and development occurs for two fundamental reasons:
o To adapt to changing environments and uses
o To implement refinements and improvements in the art of programming
The development of Java was driven by both elements in nearly equal measure.
Java is related to C++, which is a direct descendant of C, Java is inherited from these two
languages. From C, Java derives its syntax.
Java was deeply rooted in the process of refinement and adaptation that has been occurringin
computer programming languages for the past several decades.
The development of Java was driven by both elements in nearly equal measure.
History of Java:
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Simple
o Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun Microsystem, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
o Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior
o Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
o Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are
imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Applications of Java
There are many places where Java is used in real world, starting from commercial e-commerce
website to android apps, from scientific application to financial applications like electronic trading
systems, from games like Minecraft to desktop applications like Eclipse, Netbeans and IntelliJ, from
open source library to J2ME apps etc.
Let's see each of them in more detail.
Android Apps
o If you want to see where Java is used, you are not too far away. Open your Android phone
and any app, they are actually written in Java programming language. Today many Java
programmer are Android App developer. By the way android uses different JVM and
different packaging,
Server Apps at Financial Services Industry
PREPARED BY: Bhavesh Mehta Page 5 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Java is very big in Financial Services. Lots of global Investment banks like Goldman Sachs,
Citigroup, Barclays, Standard Charted and other banks use Java for writing front and back
office electronic trading system, writing settlement and confirmation systems, data
processing projects and several others.
Java Web applications
o Java is also big on E commerce and web application space. You have a lot of RESTfull
services being created using Spring MVC, Struts 2.0 and similar frameworks.
Software Tools
o Many useful software and development tools are written and developed in Java e.g. Eclipse,
InetelliJ Idea and Netbans IDE.
Trading Application
o Third party trading application, which is also part of bigger financial services industry, also
use Java. Popular trading application like Murex, which is used in many banks for front to
bank connectivity, is also written in Java.
J2ME Apps
o All games, application, which is available in Android are written using MIDP and CLDC, part
of J2ME platform. J2ME is still popular on products likes Blu-ray, Cards, Set top boxes etc.
One of the reason of WhatsApp being so popular is because it is also available in J2ME for
all those Nokia handset which is still quite big.
Embedded Space
o Java is also big in the embedded space. It shows how capable the platform is, you only need
130 KB to be able to use Java technology (on a smart card or sensor). Originally Java was
designed for embedded devices.
High Frequency Trading Space
o Java platform has improved its performance characteristics a lot and with modern JITs, its
capable of delivering performance at C++ level. Due to this reason, Java is also popular on
writing high performance systems.
Scientific Applications
o Nowadays Java is often a default choice for scientific applications, including natural
language processing. Main reason of this is because Java is more safe, portable,
maintainable and comes with better high-level concurrency tools than C++ or any other
language.
Introduction:
o Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java
Code or applications. It converts Java bytecode into machines language. JVM is a part of Java
Runtime Environment (JRE). In other programming languages, the compiler produces machine
code for a particular system. However, Java compiler produces code for a Virtual Machine
known as Java Virtual Machine.
o The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM Architecture
o Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in
Java.
Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch. It
is also known as Application classloader.
o Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
o Heap
It is the runtime data area in which objects are allocated.
o Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
o Program Counter Register
PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
o Native Method Stack
It contains all the native methods used in the application.
PREPARED BY: Bhavesh Mehta Page 7 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Execution Engine
It contains:
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts
of the byte code that have similar functionality at the same time, and hence reduces
the amount of time needed for compilation. Here, the term "compiler" refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction
set of a specific CPU.
o Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, Assembly etc. Java
uses JNI framework to send output to the Console or interact with OS libraries.
Bytecode
Bytecode is nothing but the intermediate representation of Java source code which is produced
by the Java compiler by compiling that source code.
This byte code is an machine independent code.
It is not an completely a compiled code but it is an intermediate code somewhere in the middle
which is later interpreted and executed by JVM.Bytecode is a machine code for JVM.
But the machine code is platform specific whereas bytecode is platform independent that is the
main difference between them.
It is stored in .class file which is created after compiling the source code.
Most developers although have never seen byte code.
One way to view the byte code is to compile your class and then open the .class file in a hex
editor and translate the bytecodes by referring to the virtual machine specification.
A much easier way is to utilize the command-line utility javap. The Java SDK from Sun includes
the javap disassembler, that will convert the byte codes into human-readable mnemonics.
SOURCE CODE:
import java.io.*;
class Main
{
public static void main(String args[])
BYTE CODE:
Compiled from "Main.java"
class Main extends java.lang.Object{
Main();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
}
The "javap -c" command disassembles a class file.
Disassembling done by Disassembler which converts machine language to assembly language.
TOPIC – 2
Basic OOP Concepts: Abstraction, Encapsulation, Inheritance and
Polymorphism.
Programming paradigm that views a computer program as a combination of objects which can
exchange information in a standardized manner, and can be combined with one another as
modules or blocks.
Each object is independent, can run by itself, and can be interlocked with other objects.
Objects interact by passing information among each other, and each object contains information
about itself and the objects it can interact with.
Major OOP-oriented languages are C++, Java, and Smalltalk.
Our definition of object oriented programming is : “Object oriented programming is an approach
that provided a way of modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of such modules on demand.
The major objective of object oriented approach is to eliminate some of the flaws encountered in
the procedural approach.
Concepts:
Encapsulation:
The wrapping up of data and methods into a single unit is known as encapsulation.
Data encapsulation is the most striking feature of a class.
Abstraction:
Abstraction is the act of representing essential features without including the background
details or explanation.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and methods that operate on these attributes.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
Inheritance supports the concept of hierarchical classification.
For example, the bird robin is a part of the class flying bird, which is again a part of the class
bird.
The concept of inheritance provides the idea of reusability.
This means that we can add additional features to an existing one.
The new class will have the combined features of both the classes.
Polymorphism:
Polymorphism in another important OOP concept.
Polymorphism means the ability to take more than one form.
For example, an operation may exhibit different behavior in different case. The behavior
depends upon the types of data used in the operation.
For example, consider the operation of addition for two numbers, the operation will generate
sum. If the operands are strings, then the operation would produce a third string by
concatenation.
Polymorphism plays an important role in allowing objects having different internal structures
to share the same external interface.
This means that that a general class of operations may be accessed in the same manner even
though specific actions associated with each operation may differ.
Polymorphism is extensively used in implementing inheritance.
TOPIC – 3
Comparisons Between C++ and Java.
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an
applications programming. It was interpreter for printing systems but
an extension of the C later extended as a support network
PREPARED BY: Bhavesh Mehta Page 10 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
programming language. computing. It was designed to be
easy to use and accessible to a
broader audience.
Goto C++ supports the goto statement. Java doesn't support the goto
statement.
Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the
pointer program in java. It means
java has restricted pointer support
in java.
Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts source converted into bytecode at
code into machine code so, C++ is compilation time. The interpreter
platform dependent. executes this bytecode at runtime
and produces output. Java is
interpreted that is why it is
platform-independent.
Call by Value and C++ supports both call by value Java supports call by value only.
Call by reference and call by reference. There is no call by reference in java.
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in support Java has built-in thread support.
for threads. It relies on third-party
libraries for thread support.
Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can
that we can decide whether or not override all non-static methods by
to override a function. default. In other words, non-static
methods are virtual by default.
unsigned right shift C++ doesn't support >>> operator. Java supports unsigned right shift
>>> >>> operator that fills zero at the
top for the negative numbers. For
Inheritance Tree C++ always creates a new Java always uses a single
inheritance tree. inheritance tree because all classes
are the child of the Object class in
Java. The Object class is the root of
the inheritance tree in java.
You may remember two data types already, these being floating point (represented by the float
keyword) and integer (represented by the int keyword).
Java has eight different data types, all of which represent different kinds of values in a program.
These data types are byte, short, int, long, float, double, char, and boolean.
Integer Types
The most common values used in computer programs are integers, which represent whole
number values such as 12, 1988, and -34. Integer values can be both positive or negative, or
even the value 0.
The size of the value that's allowed depends on the integer data type you choose.
Java features four integer data types, which are byte, short, int, and long.
Byte
The first integer type, byte, takes up the least amount of space in a computer's memory.
When you declare a constant or variable as byte, you are limited to values in the range -128 to
127.
In Java, you declare a byte value like this:
byte identifier;
In the preceding line, byte is the data type for the value, and identifier is the variable's name.
You can also simultaneously declare and assign a value to a variable like this:
byte count = 100;
Short
The next biggest type of Java integer is short. A variable declared as short can hold a value from
-32,768 to 32,767.
You declare a short value like this: short identifier; OR short identifier = value;
In the preceding line, value can be any value from -32,768 to 32,767, as described previously.
In Java, short values are twice as big in memory-16 bits (or two bytes)-as byte values.
Int
System.out.println("------DATA TYPES------");
System.out.println("byte: "+a);
System.out.println("short: "+b);
System.out.println("int: "+c);
System.out.println("long: "+d);
System.out.println("float: "+e);
System.out.println("double: "+f);
System.out.println("char: "+g);
System.out.println("boolean: "+h);
}
}
O/P
byte: 127
short: 32767
int: 2147483647
long: 1234567
float: 3.4
double: 9.87E-7
char: a
boolean: false
Java Operators:
Ex :-
classRelationalOp
{
public static void main(String args[])
{
int a=5,b=10,c=5;
System.out.println("a==b"+(a==b));
System.out.println("a!=b"+(a!=b));
System.out.println("a>b"+(a>b));
System.out.println("a<b"+(a<b));
System.out.println("a>=b"+(a>=b));
System.out.println("a<=b"+(a<=b));
}
Ex :-
public class AssignmentOp
{
public static void main (String[] args)
{
int a=1,b=10;
a+=5;
b=b+5;
System.out.println(a);
System.out.println(b);
}
}
Output :
6
15
(4) Bitwise Logical Operator:
Operator Use Operation
& op1 & op2 Bitwise and
| op1 | op2 Bitwise or
^ op1 ^ op2 Bitwise xor
~ ~op2 Bitwise complement
Output :
Absolute value of i = 10
TOPIC – 5
Control Statements, Arrays and Command Line Arguments.
Control Statements:
(1) If … else
The If statement enables your program to selectively execute other statements, based on some
criteria.
This is the simplest version of the if…else statement: The block of statements will be executed
if a condition is true.
Generally, the simple form of if can be written like this:
if (expression)
{
True statement
}
else
{
False Statement
}
What if you want to perform a different set of statements if the expression is false? You use the
else.
The else block is executed if the if part is false. Another form of the else statement.
Class ifelse
{
public static void main(String arg[])
{
int a=10,b=20;
if(a>b)
{
System.out.println("a is greater than b");
}
else
{
System.out.println("b is greater than a");
}
}
}
Output :
b is greater than a
(2) Switch … case
statement to conditionally perform statements based on an integer expression.
Following is a sample program, SwitchDemo, that declares an integer named month whose
value supposedly represents the month in a date.
While loop
You use a while statement to continually execute a block of statements while a condition
remains true.
The general syntax of the while statement is:
while (expression)
{
Statement;
}
First, the while statement evaluates expression , which must return a boolean value.
If the expression returns true, then the while statement executes the statement(s) associated
with it.
The while statement continues testing the expression and executing its block until the
expression returns false.
Ex :-
public class While
{
public static void main(String[] args)
{
int i=5;
while(i>0)
{
System.out.println("i="+i);
PREPARED BY: Bhavesh Mehta Page 20 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
i--;
}
}
}
Output :
i=5
i=4
i=3
i=2
i=1
(3) do … while loop
The Java programming language provides another statement that is similar to the while
statement, the do-while statement.
The general syntax of the do-while is:
do
{
statement(s);
} while (expression);
Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at
the bottom.
Thus the statements associated with a do-while are executed at least once.
Class dowhile
{
public static void main(String args[])
{
int i=5;
do
{
System.out.println("i="+i);
i--;
}while(i>0);
}
}
Output :
i=5
i=4
i=3
i=2
i=1
(4) for loop
The for statement provides a compact way to iterate over a range of values.
The general form of the for statement can be expressed like this:
for (initialization;condition;increment/decrement)
{
Statements;
}
The initialization is an expression that initializes the loop-it's executed once at the beginning of
the loop.
The conditional expression determines when to terminate the loop.
This expression is evaluated at the top of each iteration of the loop.
PREPARED BY: Bhavesh Mehta Page 21 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
When the expression evaluates to false, the loop terminates.
Finally, increment or decrement is an expression that gets invoked after each iteration through
the loop.
Ex :-
public class ForLoop
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
System.out.println("i="+i);
}
}
}
Output :
i=1
i=2
i=3
i=4
i=5
(5) Labeled Loop OR Outer Loop
A label is an identifier placed before a statement.
The label is followed by a colon (:).
The labeled form of the continue statement skips the current iteration of an outer loop marked
with the given label.
Ex :- Print only odd number between 1 to 10 using Label Loop or Outer Loop
Class LabelLoop
{
public static void main(String args[])
{
outer : for(int m=1;m<11;m++)
{
if(m%2==0)
{
continue outer;
}
else
{
System.out.println(m);
}
}
}
}
(6) Using Break- Exit from a Loop
By using break, you can force immediate termination of a loop, bypassing theconditional
expression and any remaining code in the body of the loop.
When a breakstatement is encountered inside a loop, the loop is terminated and program
controlresumes at the next statement following the loop.
Ex :-
PREPARED BY: Bhavesh Mehta Page 22 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 6) break; // terminate loop if i is 6
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output :
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
Loop complete.
(7) Continue statement
You use the continue statement to skip the current iteration of a for, while , or do-while loop.
The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean
expression that controls the loop, basically skipping the remainder of this iteration of the loop.
Ex :-
class Continue
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.print(i+" ");
if(i%2==0) continue;
System.out.println();
}
}
}
Output :
01
23
45
67
89
(8) Return statement
The last of Java's branching statements is the return statement.
You use return to exit from the current method.
The flow of control returns to the statement that follows the original method call.
The return statement has two forms: one that returns a value and one that doesn't.
To return a value, simply put the value (or an expression that calculates the value)
o after the return keyword:
When a method is declared void, use the form of return that doesn't return a value.
PREPARED BY: Bhavesh Mehta Page 23 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Ex :-
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
Output :
Before the return.
Array in java
Output :
Days of April month are = 30
Sometimes you will want to pass information into a program when you run it.
This isaccomplished by passing command-line arguments to main( ).
A command-line argument isthe information that directly follows the program’s name on the
command line when it isexecuted.
To access the command-line arguments inside a Java program is quite easy—they are stored as
strings in a String array passed to the args parameter of main( ).
The firstcommand-line argument is stored at args[0], the second at args[1], and so on.
For example,the following program displays all of the command-line arguments that it is called
with:
// Display all command-line arguments.
classCommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
Try executing this program, as shown here:
JavaCommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
TOPIC – 6
Structure of Java Programming.
Let's see which elements are included in the structure of a Java program. A typical structure of
a Java program contains the following elements:
o Documentation Section
o The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program.
o The information includes the author's name, date of creation, version, program name,
company name, and description of the program.
o It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program.
o To write the statements in the documentation section, we use comments. The comments
may be single-line, multi-line, and documentation comments.
o Single-line Comment: It starts with a pair of forwarding slash (//). For example:
o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
o Package Declaration
o The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed.
o Note that there can be only one package statement in a Java program. It must be defined
before any class and interface declaration. It is necessary because a Java class can be
placed in different packages and directories based on the module they are used.
o For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:
package javatpoint; //where javatpoint is the package name
package com.javatpoint; //where com is the root directory and javatpoint is the subdire
ctory
o Import Statements
o The package contains the many predefined classes and interfaces. If we want to use any
class of a particular package, we need to import that class.
o The import statement represents the class stored in the other package. We use
the import keyword to import the class. It is written before the class declaration and after
the package statement.
o We use the import statement in two ways, either import a specific class or import all
classes of a particular package. In a Java program, we can use multiple import statements.
For example:
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all the class of the java.util package
o Interface Section
o It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the
class.
o It contains only constants and method declarations. Another difference is that it cannot
be instantiated. We can use interface in classes by using the implements keyword.
o An interface can also be used with other interfaces by using the extends keyword. For
example:
interface car
{
void start();
void stop();
}
o Class Definition
o In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program.
o A Java program may conation more than one class definition. We use the class keyword to
define the class. The class is a blueprint of a Java program.
o It contains information about user-defined methods, variables, and constants. Every Java
program has at least one class that contains the main() method. For example:
class Student //class definition
{
}
From the Start menu, select the Command Prompt application (Windows XP). When the
application launches, it should look like this:
The prompt shows your current directory. When you bring up the prompt for Windows XP,
your current directory is usually WINDOWS on your C drive. To compile your source code file,
change your current directory to the directory where your file is located. For example, if your
source directory is java on the C drive, you would type the following command at the prompt
and pressEnter:
cd c:\java
Now the prompt should change to C:\java>.
If you enter dir at the prompt, you should see your file.
Now you can compile. At the prompt, type the following command and press Enter:
javac HelloWorldApp.java
The compiler has generated a Java bytecode file, HelloWorldApp.class. At the prompt, type dir
to see the new file that was generated:
Running a program :
In the same directory, enter at the prompt: “java HelloWorldApp”