Professional Documents
Culture Documents
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
T-SEM III
Chapter 1: Introduction
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. 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.
5) Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7) 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.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).
1
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Java C++
Java is pure object oriented programming C++ is semi object oriented language b'coz
language. We can't design and develop our we can design and develop our programs and
programs and applications without object. applications, with and without object.
Java is Dynamic, Java allocates memory at run- C++ is static, C++ allocates memory at
time. compile-time.
Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.
Java doesn't support multiple inheritance. Java C++ does support multiple inheritance.
uses interface for multiple inheritance.
Java supports automatic garbage collection. Java C++ does support destructors, which is
does not support destructors as C++ does. automatically invoked when the object goes
out of scope.
Java does not support default argument value. C++ does support default argument 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, which is platform independent. code may not run on different platforms.
2
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
According to Sun, Java language is simple because:
Syntax is based on C++ (so easier for programmers to learn it after C++).
Removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
3
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
1. Runtime Environment
2. API(Application Programming Interface)
4
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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
Classloader: adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
Bytecode Verifier: checks the code fragments for illegal code that can violate access
right to objects.
Security Manager: determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language. Some security can also be provided by application
developer through SSL, JAAS, Cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points makes java robust.
Architecture-neutral
5
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications etc.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It
is the implementation of JVM. It physically exists. It contains set of libraries + other files that
6
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
JVM uses at runtime. Implementation of JVMs is also actively released by other companies
besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development
tools.
7
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
8
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
7) Execution Engine
It contains:
1) A virtual processor
3) 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.
9
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
These tasks are described in detail in the subsequent sessions. A detailed Java architecture can
be drawn as given below.
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. It checks the byte code and ensures the followings.
1. The code follows JVM specifications.
2. There is no unauthorized access to memory.
3. The code does not cause any stack overflows.
4. There are no illegal data conversions in the code such as float to object references.
10
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
You might have noticed the component “Just in Time” (JIT) compiler in Figure 3. This is a
component which helps the program execution to happen faster.
As we discussed earlier when the Java program is executed, the byte code is interpreted
by JVM. But this interpretation is a slower process. To overcome this difficulty, JRE
include the component JIT compiler. JIT makes the execution faster.
If the JIT Compiler library exists, when a particular bytecode is executed first time, JIT
complier compiles it into native machine code which can be directly executed by the
machine in which the Java program runs. Once the byte code is recompiled by JIT
compiler, the execution time needed will be much lesser. This compilation happens
when the byte code is about to be executed and hence the name “Just in Time”.
Once the bytecode is compiled into that particular machine code, it is cached by the JIT
compiler and will be reused for the future needs. Hence the main performance
improvement by using JIT compiler can be seen when the same code is executed again
and again because JIT make use of the machine code which is cached and stored.
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.
11
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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:
12
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.6.0_23\bin
13
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
For setting the permanent path of JDK, you need to follow these steps:
o Go to MyComputer properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable value -
> ok -> ok -> ok
For Example:
1)Go to MyComputer properties
14
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
15
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
16
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
8)click on ok button
9)click on ok button
Now your permanent path is set. You can now execute any program of java from any drive.
export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).
17
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Path:
Path variable is set for providing path for all Java tools like java, javac, javap, javah, jar, applet
viewer. In Java to run any program we use java tool and for compile Java code use javac tool.
All these tools are available in bin folder so we set path up to bin folder.
classpath:
classpath variable is set for providing path of all Java classes which is used in our application. All
classes are available in lib/rt.jar so we set classpath upto lib/rt.jar.
Path classpath
path variable is set for providing path for all classpath variable is set for provide path
java tools like java, javac, javap, javah, jar, of all java classes which is used in our
appletviewer application.
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"
18
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
All the tools are present in bin folder so we set path upto bin folder.
Classpath variable is used to set the path for all classes which is used in our program so we set
classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed rt.jar
file we get all .class files.
Example
"C:\Program Files\Java\jre1.6.0\jre\lib\rt.jar"
In above rt.jar is a jar file where all the .class files are present so we set the classpath upto
rt.jar.
6. Java API
Java compiler
Java Virtual Machine (JVM)
Java Application Programming Interface (API)
19
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
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.
7. Java Platform
20
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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:
Java Card: A technology that allows small Java-based applications (applets) to be run
securely on smart cards and similar small-memory devices.
Java ME (Micro Edition): Specifies several different sets of libraries (known as profiles) for
devices with limited storage, display, and power capacities. It is often used to develop
applications for mobile devices, PDAs, TV set-top boxes, and printers.
Java SE (Standard Edition): For general-purpose use on desktop PCs, servers and similar
devices.
Java EE (Enterprise Edition): Java SE plus various APIs which are useful for multi-tier client–
server enterprise applications.
The Java platform consists of several programs, each of which provides a portion of its overall
capabilities. For example, the Java compiler, which converts Java source code into Java
bytecode (an intermediate language for the JVM), is provided as part of the Java Development
Kit (JDK). The Java Runtime Environment(JRE), complementing the JVM with a just-in-time (JIT)
compiler, converts intermediate bytecode into native machine code on the fly. The Java
platform also includes an extensive set of libraries.
The essential components in the platform are the Java language compiler, the libraries, and the
runtime environment in which Java intermediate bytecode executes according to the rules laid
out in the virtual machine specification.
In most modern operating systems (OSs), a large body of reusable code is provided to simplify
the programmer's job. This code is typically provided as a set of dynamically loadable
libraries that applications can call at runtime. Because the Java platform is not dependent on
any specific operating system, applications cannot rely on any of the pre-existing OS libraries.
Instead, the Java platform provides a comprehensive set of its own standard class libraries
containing many of the same reusable functions commonly found in modern operating systems.
Most of the system library is also written in Java.
21
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
First Java Program
Let us look at a simple code that will print the words Hello World.
Example
public class MyFirstJavaProgram
{
public static void main(String []args)
{
System.out.println("Hello World"); // prints Hello World
}
}
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.
Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
22
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hellowould
have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.
interface name-- should start with uppercase letter
variable name-- should start with lowercase letter e.g. firstName, orderNumber etc.
package name -- should be in lowercase letter e.g. java, lang, sql, util etc.
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.
23
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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;
//without lambda, Drawable implementation using anonymous class
Drawable d=new Drawable(){
public void draw(){System.out.println("Drawing "+width);}
};
d.draw();
} }
24
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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. In this tutorial, we are explaining method reference
concept in detail.
25
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
3. Reference to a constructor.
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.
26
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Syntax
containingObject::instanceMethodName
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
// Referring non-static method using reference
Sayable sayable = methodReference::saySomething;
// Calling interface method
sayable.say();
// Referring non-static method using anonymous object
Sayable sayable2 = new MethodReference()::saySomething;
// You can use anonymous object also
// Calling interface method
sayable2.say();
}
}
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.
27
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Syntax: ClassName::new
Example
interface Messageable
{
Message getMessage(String msg);
}
class Message
{
public Message(String msg)
{
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
28
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as input.
1. We give complete program as input to the compiler. Our program is in the human
readable format.
2. Human readable format undergoes many passes and phases of compiler and finally it is
3. However interpreter takes single line of code as input at a time and execute that line. It
will terminate the execution of the code as soon as it finds the error.
29
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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:
3. Embedded Systems:
Embedded systems, ranging from tiny chips to specialized computers, are components of larger
electromechanical systems performing dedicated tasks. Several devices, such 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.
The Java ecosystem today contains multiple Java web servers and application servers. While
Apache Tomcat, Simple, Jo!, Rimfaxe Web Server (RWS) and Project Jigsaw dominate the web
server space, WebLogic, WebSphere, and Jboss EAP dominate commercial application server
space.
30
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
Statements are similar to sentences in the English language. A sentence forms a complete idea
which can include one or more clauses. Likewise, a statement in Java forms a complete
command to be executed and can include one or more expressions.
In simpler terms, a Java statement is just an instruction that explains what should happen.
There are three main groups that encompass the different kinds of statements in Java:
Expression statements change values of variables, call methods, and create objects.
Declaration statements declare variables.
Control flow statements determine the order that statements are executed. Typically,
they're understood from top to bottom. However, with control flow statements, that
order can be interrupted to implement branching or looping so that the Java program
can run particular sections of code based on certain conditions.
//declaration statement
int number;
//expression statement
number = 4;
31
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
if (number < 10 )
{
//expression statement
System.out.println(number + " is less than ten");
}
public static void main(String args[]) is the main method in Java. M ain 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 ).
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 −
Return Value
This method returns true, if the passed character is really a white space.
32
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Example
Output
false
true
true
true
17. Keywords
Keywords have special meaning to the Java compiler. They help in identifying a data type name
or program construct name.
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.
33
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Syntax:
Example:
Output:
10
Syntax:
Example:
34
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
int i=10;
System.out.println(i);
}
}
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.
35
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
Example:
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.
36
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III
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.
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class
37