CORE JAVA
CORE JAVA
JAVA
Object Oriented Program is a programming approach in which a
problem domain is characterized as a set of objects that have a
specific attributes and behavior. The objects are manipulated with
a collection of functions called methods or services. The objects
are classified into classes and subclasses. (or) An Object Oriented
Programming organizes a program around its data, i.e., objects and
a set of well-defined interfaces to that data. An object-oriented
program can be characterized as data controlling access to code.
Java is an Object Oriented Programming (OOP) language used to
design an application, which will run securely over the network and
work on wide range of platforms.
J2SE: - J2SE stands for Java 2 Standard Edition, it is a
specification used to develop fundamental java application they may
be standard or network.
J2SE = Core Java + Advanced Java
J2SE: - Java 2 Standard Edition
J2EE: - Java 2 Enterprise Edition
J2EE: - J2EE stands for Java 2 Enterprise Edition, it is a
specification used to develop business solutions for network (or)
J2EE is a specification that provides an environment to run the web
components and the enterprise components.
J2ME: - Java 2 Micro Edition
J2ME: - J2ME stands for Java 2 Micro Edition, it is a
specification used for developing wireless and Embedded System.
Embedded System is software, which directly installed into
hardware.
Difference between Java 1.4.1. and Java 1.5 [www.sunjava.com,
www.javasoft.com]
Core Java Desktop Java
NIC Network Interface Card
Novel Network: - Net based softwaressEx: - Windows NT, UNIX.
Protocol: - This is also a program; it is a specification of set
of rules to be followed by a computer in network.
When to send/receive data
How to send/receive data
Hand Shaking: - This means two Computers establishing a
connection communicating with each other and finally disconnecting
is called Hand shaking.
A Packet represents a group of bytes. IP means Internet Protocol
address this is unique address this is given to Computers.
TCP/IP: - Transmission Control Protocol/Internet Protocol.
Client: - A Client is a machine that sends a request for some
services to other Computer.
Server: - Server is a machine that receives requests from the
Clients and provides services to the Client requests.
The main advantage of a network is resources sharing.
Web application: - A web application is a collection of
Servlets, HTML pages, Classes and other resources that can bundle
and run on the multiple Containers from multiple Vendors. Resources
Sharing: -
Sharing memory
Sharing data
Sharing software
Sharing hardware
Sharing Processor
1969 Department of Defence (DOD), USA, Ken Thompson is
introduced network. This network is called ARPANET.
( (
(
(AT&T Advanced Telephone Communication & Technology USA
based Telephone Company.
Hyundai, British Telecom are also Telephone companies, these
three companies are giant of the Telephone.
ISP: - It stands for Internet Service Provider. ISP is a person
or an organization, who provides connection into internet. ISP
should take direct connection to internet. (www.internic.com).
Bandwidth is a group of frequency.
American Congress Library is a biggest Library in the World; the
second biggest Library is Lenin Glad Library in Masco,
(Russia).
Q) What is an Interface? *****
Ans: - An Interface defines a protocol of behavior that can be
implemented by any class anywhere in the class hierarchy. An
interface defines a set of methods but doesnt implement them. A
class that implements the interface agrees to implement all the
methods defined in the interface, thereby agreeing to certain
behavior.
An interface is a named collection of method definitions
(without implementations). An interface can also declare
constants.
Internet: - Internet is a network of Computers existing on the
earth. Internet is a global network of all networks existing on the
earth.
Connecting Internet types: -
Dialup Connection: -
Dialup connection main advantage is affordable to any one.
Disadvantage of Dialup connection is slow.
There is no security for data.
2. Leased line Connection: - It is a direct connection to
internet.Advantages: -
High Security for data
Lightening Speed (i.e. high speed)
Disadvantages: -
Highly expensive.
The web browser software is installed on Internet Client.
Ex: - Internet Explorer, Mozilla, Fire fox, Netscape Navigator
etc
The software that should be installed on Internet Server is Web
Server.
Web Server: - A web server is a server that provides the
implementation of HTTP protocol.
Ex: - Internet information Server (IIS), Apache Web Server,
etc
Application Server: - An Application Server is a product that
provides the facilities like taking care of transactions, taking
care of security and simplifies the development of business logic
(or) Application servers provides you with common middleware
services, such as resource pooling, networking and more.
Application server allows you to focus on your application and not
worry about the middleware you need for a robust server side
deployment.
Ex: - Microsoft Transactions Server (MT Server) from Microsoft,
EJB containers like WebLogic, WebSphere, JBoss etc
Hypertext Transfer Protocol (HTTP) is widely used protocol on
internet.
File Transfer Protocol (FTP), when we download a file from
Internet.
Simple Mail Transfer Protocol (SMTP) is used to send mails on
the internet.
Post Office Protocol (POP) is used to receive mails.
Programmer has: -1. To develop a web browser
2. To increase the capabilities of web browser
3. To develop a web server
4. To increase the capabilities of the web server
5. To develop protocol
Translator is a program that converts a computer program into
machine language (Electric Pulses).
There are 3 types of translators -
1. Interpreter Interpreter translates line by line of computer
program
2. Compiler Compiler translates all lines of program at a single
time
3. AssemblerAssembler translates assembly language into machine
language
C, C++, are not portable programs, they are system dependent
because they can be executed only on that system where they are
developed.
The first microprocessor is - 4 0 0 4
The next microprocessors are follows as below
8 0 0 8
8 0 8 5
8 0 8 6
8 0 2 8 6
8 0 3 8 6
8 0 4 8 6
8 0 5 8 6x, PI, PII, Celeron, PIII, AMD, PIV, PIV Pro
Why Java is suitable for Internet
The size of each instruction is 1 byte or 8 bits. There are
around 210 byte code instructions are available
Byte code instruction is understand by JVM (Java Virtual
Machine).Components of JVM
JVM
Sun Microsystems is developed the JVM program.
JVM convert byte code instruction into machine code. JVM
understand every byte code instructions.
JVM will understand the byte code instruction & it will
convert the byte code instructions into PIV processor
understandable machine language instructions.
JVM will convert the byte code instructions into any type of
processor understandable machine language instructions.
Java programs system independent.
JVM is system dependent.
Depending on operating system we have to download the operating
system related JVM program.
.class file is system independent.
JVM is making as Java system independent.
Portability means giving same results on any type of system or
machine.
Security Problems on Internet: -
1. Eves dropping: - Reading others data illegally on Internet,
is called Eves dropping.
2. Tampering: - Not only reading others data but also modifying
it on Internet, is called Tampering.
3. Impersonation: - A person acting as another person on
Internet is called impersonation.
4. Virus: - Virus is a harmful program that can damage data,
software & hardware of a system.
Virus was first developed by Pakistanis. Virus will spread to
*.exe, *.sys, *.doc. but *.txt files cannot carry virus.
Solution for eves dropping & tampering
encryption/decryption. Encryption means converting data into
understandable data. Decryption means converting data back to
readable form.
For impersonation, solution is digital signature file,
containing personal information for identify the person in
encrypted form. Digital signatures are developed in java.
Solution for virus is .class file. Security manager is program
that identifies illegal code and information security polices. A
.class is a text file virus cant be affected.
Why Java is suitable for Internet: -
Security problems on Internet are eliminated through java.
Java is a system independent; Java is executable on any
platform.
In 1990, Sun Microsystems inc., USA is developed software for
remotes. (James Gosling).
In 1993, Oak language is developed, by that time some company is
registered Oak name, for this reason they named as Java.
In 1995, Sun world conference has given entire details of
Java.
Features of Java: -
1. Simple: - Java is a simple programming language, learning and
practicing java is easy because of its resemblance (Similarity)
with C, C++.
2. Object Oriented: - Unlike C++, Java is a purely object
oriented programming language.
Java = C++ - Complexity
An object is existing of everything in the world is an Object.
An object has properties & performs actions.
Object initialization process: -
Default values ( initialization expressions ( initialization
blocks ( constructors
Default values: -
float, double
-0.0F,0.0
boolean
-false
Reference variable
-null (not referring any object)
Char
-\u000 (or) a space
String
-Null
My class
-Null
3. Distributed: - Java is designed for use on networks. It has
extensive libraries, which work in agreement with TCP/IP. Java uses
protocols like HTTP & FTP.
4. Robust: - Java programs will not crash because of its
exception handling and its memory management feature.
Pointers are eliminated from Java due to: -
1. These are lead to complex programs
2. Using pointers harmful programs are written.
3. Pointers may crash a program.
Method is a function; Function represents set of instructions to
perform the results. A method must be starts with lowercase. A
method will returns a void or any valid return type. A method can
be inherited and it can be overloaded or overridden. A method has
called explicitly.
Function can be written inside & outside of the class, but a
method is a function, it is written only inside of a class. A
function can be called & executed itself.
Q) What is the difference between method and function? *****
Ans: - A method is a function written only inside of a class but
functions can be written any where in class i.e. inside or outside
of the class. In java we will write only methods. Writing a
function outside the class is not possible in java.
Methods or functions can store only some temporary variables or
local variables, but not permanent variables.
A class is a model or idea or plan to create objects or Class is
a group of objects. Class doesnt exist really because it is only an
idea but objects exist really.
A class will also contain variables & methods. An object
will also contain variables & methods. In every java program we
must create a single class. C++ is not purely Object oriented
programming Internet is a distributed technology. Java is suitable
for distributed technology. Robust means strong, in java we can
write strong programs. Exception means runtime error
JVM will allot memory to what ever we required memory.
Unused memory released or free it by JVM
Garbage Collector will delocate or removes memory for
unreferenced or unused objects and variables.
Garbage Collector can be called explicitly but there no gurantee
that the garbage collector executes or not at that point.
Q) What algorithm is used by garbage collector to remove
variables or objects from memory? *****
Ans: - Mark & Sweep algorithm.
Q) What is the difference between .exe and .class file?
*****
Ans: - .exe file contains machine language instructions for the
microprocessor. It is system dependent. .class file contains byte
instructions for JVM. It is system independent.
In JVM class loader sub system will allot the memory required
for program.
Garbage memory delocates the memory.
5. Secure: - Java is designed for use on internet. Java enables
the construction of virus-free, tamper free systems.
6. Architecture Neutral: - Javas byte code is not machine
dependent. It can be run any machine with any processor and any
operating system.
7. Portable: - Java does not have implement-dependent aspects.
So the results will be same on all machines. Portable means
yielding same results on different machines.
8. Interpreted: - Java programs are compiled to generate bye
code. This byte code can be downloaded and interpreted by the
interpreter. JVM contain interpreter.
9. High performance: - Along with interpreter there will JIT
(Just in time compiler), which enhances the speed of execution.
Variable: - An item of data named by identifier. Each variable
has a type, such as int or object and a scope. Reference Variable:
- A data element whose value is in an address.
Local Variable: - A data item known within a block, but
inaccessible to the code outside the block.
For example, any variable defined within a method is a local
variable and cant be used outside the method.
A local variable life cycle ends when the execution of method
completed. A local variable should declared within a method body
and it must be initialized when we are declaring in a method,
because it doesnt takes default values.Path Variable: - It is
exterenal command file. A path variable is used to specify where
the executable files are.
Ex: - javac.exe, java.exe, javap.exe etc. Argument: - A data
item specified in a method called an argument. An argument can be a
literal value, a variable or an expression (or) an argument is a
value that is passed to the method when it is invoked.
Parameter: - While defining a method, variables passed in the
method called as parameter (or) Parameters are variables defined by
method that receives values when a method is called.
Parameters are useful to pass the variables from objects to the
constructor.
Method parameters are local variables to receive the data from
out side for method.
Parameters are useful to receive the values from outside to main
method.
What is the difference between parameter and argument? *****
Ans: - While defining method, variables passed in the method
called as parameter. While using those methods, values passed to
those variables called arguments.
Process: A virtual address space containing one or more threads
(or) a program under execution is also called as process.
Peer: - In networking, any functional unit in the same layer as
another entity.
Expression: - An expression is a series of variables, operators,
and methods calls, (constructed according to the syntax of the
language) that evaluates to single value.
How would you detect and minimise memory leaks in Java: -
In Java memory leaks are caused by poor program design where
object references are long lived and the garbage collector is
unable to reclaim those objects.
Detecting memory leaks:
Use tools like JProbe, OptimizeIt etc to detect memory
leaks.
Use operating system process monitors like task manager on NT
systems, ps, vmstat, iostat, netstat etc on UNIX systems.
Write your own utility class with the help of totalMemory() and
freeMemory() methods in the Java Runtime class. Place these calls
in your code strategically for pre and post memory recording where
you suspect to be causing memory leaks. An even better approach
than a utility class is using dynamic proxies or Aspect Oriented
Programming (AOP) for pre and post memory recording where you have
the control of activating memory measurement only when needed.
Minimising memory leaks:
In Java, typically memory leak occurs when an object of a longer
lifecycle has a reference to objects of a short life cycle. This
prevents the objects with short life cycle being garbage collected.
The developer must remember to remove the references to the
short-lived objects from the long-lived objects. Objects with the
same life cycle do not cause any issues because the garbage
collector is smart enough to deal with the circular references.JVM
Architecture: - JVM 1.4.1 version developed by Hotspot.
Class loader subsystem does the following things: -
1. It will load .class file into memory (RAM)
2. It will verify byte code of that .class file.
3. It will allot the required memory for the program.
This memory is divided into five parts; they are called runtime
data areas.
1. Method area: - It stores class code, static variables, static
blocks and method code.
2. Heap area: - Objects are created on Heap. JVM creates objects
on Heap.
3. Java Stacks: - Java stacks are used to execute the java
methods. Java stacks will have frames. On each frame a separate
method is executed.
4. PC Registers: - These registers contain the address of that
instruction to be executed by the processor.
5. Native method stacks: - It is a method written in a language
other than java. Native method stacks places when native methods
are executed.
Note: - Native method interface links header files to a native
method while it is being executing.
Execution engine contains interpreter & JIT compiler, which
translates byte code into machine language.
How JIT compiles converts byte codes.
Ex: - print a; 2sec
print b; 2sec
Repeat the loop 10times;
print a; 2 + 2
Hotspot is the block code of given to JIT compiler for
execution.
10. Multithread: - Thread means an execution or processing group
of statements. Executing different parts of a program
simultaneously at a time by using more than one thread is called
Multithreading. This is an essential feature of to design server
side programs.
11. Dynamic: - It means at runtime, we can develop programs in
java, which dynamically change on Internet. (Ex: Applets).
In java entire memory will be dynamic memory.
Java Programming: -
Comments represent description of the features of a program.
The main advantages of comments are readability of the program
is increased.
There are 3 types of comments in Java. They are
1. Single line comments: - It represents only one line as
comment. Single line comments start with //.
Ex: - //Welcome INet Solv
//welcome to Java
2. Multi line Comments: - They represents a group of lines as
comment. They starts with /* and end with */
Ex: - /*Welcome to India*/
3. Java documentation Comments: - They starts with /** and end
with */.
Ex: - /**Welcome to BTCE*/
These comments are useful to create .html documents from .java
programs.API Document: - API stands for Application programming
Interface. It is a .html document that contains description of all
the features of a software or a product or a technology. API
document does not contain code. Javadoc complier is used for
this.
Comments are non executable statements. These 3 types of
comments are not executable by java compiler or JVM compiler.
In Java we can define/write any number of classes in a single
class. Out of n number of classes we are writing in a single class
only one can be defined as public class, because the name of the
class should be public class.
If we need all the classes as public we have to decalred/write
sepeartely each class as public.
Example Program: -
/*This is our first Java program.
To display a message
Author: INet Solv team
Version: V 1.0
Project: Proxyz 1.11
*/
//Starting a program in Java
import java.lang.system;
import java.lang.string; or in the place of two steps directly
we can write as below
import java.lang.*;
class First
{
main()
{
---------------
---------------
---------------
}
}
Q) What is the difference between #include and import
statements? *****
Ans: - #include makes C/C++ compiler to copy the header file
into a C/C++ program. Thus it wastes the memory and processor
time.
import will makes the JVM to go to a particular class, it
executes the code there and then it comeback to the program and
substitute the results in the program.
JRE: - It stands for Java runtime environment.
JRE = JVM + Java library
If java programs have to run we required the JVM and java
library. JVM will starts execution of java program from main method
only.
String represents group of characters.
Array represents group of elements. Array denotes with [ ]
The values passed to the main method are called command line
arguments.
Void means no value (i.e. it returns no value).
import java.lang.*;
class First
{
main()
{
-------------
-------------
-------------
}
}
To call method there are two steps: -
1. To create on object to the class to which method belongs
Classname obj = new Classname();
Ex: - First f = new First();
((f = object)
2. Call the method using object name.methodname
Obj.methodName();
Ex: - f.main();
Objects are created dynamically (runtime) by JVM
Static method: - It is a method that can be called and executed
without creating an object.
Public: - It means available outside the object. JVM will not
run the public without writing String args[]. JVM could not
executes the main method.
For single character in java we have to write in single
quotations like as a and for integer dont write in any
quotations.
System.out: - Out is a variable of a system class. It is a
static variable or filed.
Save the name with in double quotations to avoid the extension
of .txt.
System.out.println(): -
System: - System is a predefined final class which is defined in
java.lang package that provides the access to the system resources
like Keyboard, monitor etc and to get and set the properties
associated with java runtime system. All the methods in the System
class are static methods.
System Class: - A System class will have static members, they
are as follows below PrintStream out, err
InputStream in;
arrayCopy(Object[ ], st, end, Object[ ], st)
exit(int)
loadLibrary(String)
get/setSecurityManager(SecurityManager)
String getProperty(String)
String getProperties(String str) (getProperties() method is
usefull to get the JVM name, version, properties of JVM and
etc.).
Properties getProperties() (Property is a class in java.util
package and getProperties() method is usefull to set/get the
property of a class, etc.).
gc()
out: - out is a static variable defined in a System class of the
type PrintStream class, which provides all of the formatting
capabilities we have been using from the system file handler or out
is the PrintStream object.
println(): - println() is a built-in overloaded method in the
out object or the PrintStream object supports the print() or
println() methods for all data types.
We can provide a security for a class as below:
public static void main(String args[ ]){
System.setSecurityManager(new SecurityManager());
---------------
---------------
---------------
}
To Compile: -
C:\rnr>javac First.java(
C:\rnr>java First(
Welcome to java
Class, interface contains methods.
Function is written inside & outside of the class, but
methods are written only inside of the class.
Command line arguments are passed some values to the main
method.
Main method does not return any value. Void means no value.
JVM always starts execution of the statements inside of the main
method.
Public is written to make available main method to the JVM.
Ex 2: -
//To find sum of two numbers
import java.lang.*;
((* is a String class)
class Sum
{
({ ----This is for starting of class)
public static void main(String args[ ])(String args[ ] is a
parameter)
{
//Variables
int a, b;
//Store data into variables
a = 10;
b = 15;
//Now find sum
int c = a + b;
//display the result
System.out.println(Sum = ,+c);
}
}
((} ----This is for ending of class)
(or)
//To find sum of two numbers
import java.lang.*;
class Sum
{
public static void main(String args[ ])
{
//Variables
int a, b;
//Store data into variables
a = 10;
b = 15;
//display the result
System.out.println(Sum = + (a+b));
}
}
Save the above file (with class name compulsory) as Sum.java
C:\rnr>javac Sum.java(
(This is for program compilation)
C:\rnr>java Sum.java(
(This is to run the program)
Note: -
1. print method displays the results and keeps the cursor in the
same line.
2. println method displays the results and then throws the
cursor to the next line.
S. No.Back slash codes
or escape sequenceMeaning
1.\nNew line
2.\rEnter key
3.\tHorizontal tab
4.\bBackspace key
5.\\\
6.\
7.\
In java every statement must end with semi colon (;).
Java is case sensitive programming language.
Naming Conventions in Java: - 1. Each word of class names and
interface names start with a capital letter.
Ex: - String, StringBuffer, DataInputStream, ActionListener
etc2. Packages names in java are written in all small letters.
Ex: - java.awt, java.io, java.swing etc
3. Method names start with a small letter, then each word start
with a capital letter.
Ex: - println(), getChars, readLine(); getNumberInstance()
etc
4. Variables names also follow the above rule.
Ex: age, empName, employee_Net_Sal etc
5. Constant variables should be written using all capital
letters.
Ex: - PI, MAX_VALUE, FONT.BOLD
Note: - java.lang is a package that is by default imported into
every java program. The other packages must be imported in java
program.
Important packages of Java: -
1. java.lang: - This package got primary classes and interfaces
essential for java language. It consists of wrapper classes,
strings, multithreading etc.
Wrapper classes are useful to create objects
String is a class in java
Multithreading means create several threads (processes
executing) at a time.
2. java.util (util = utility): - This package contains useful
classes and interfaces like stack, LinkedList, Hashtable, Arrays
etc.
3. java.io: - This package handles files and input/output
related tasks.
4. java.awt (awt = abstract window toolkit): - This package
helps to develop GUI (Graphical user interface). It consists of 2
important sub packages, namely: java.awt.event and
java.awt.image.
5. javax.swing: - x stands for extended package. The classes in
this package have been derived from other package. This package
helps to develop GUI like java.awt.
6. java.net: - net stands for network. Client/Server programming
can be done using this package. It uses TCP/IP internally.
7. java.applet: - Applets are small intelligent programs, which
travel form one place to another place on internet.
8. java.sql: - sql stands for structure query language. This
package helps to connect to databases like oracle and utilize them
in java.
9. java.beans: - Beans are software reusable components. They
can be developed using this package.
10. java.rmi: - rmi means remote method invocation. The objects,
which exist on one computer in the network, can be invoked from
another computer and can be used.
11. javax.servlet: - Servlets are server side programs which
communicate several clients at a time. Servlets are server side
programs, which handle clients. This package is useful to develop
servlets.
Class is model for creating objects. In case we have to write
methods & variables. Data types represent the type data stored
into variable (i.e. into memory locations).Data types and literals:
- A data type represents the type of data stores in memory
(variable).
Integer data type: - It represents integer numbers i.e. the
numbers without decimal points.
Subtype: -
S. No.Data typeMemory sizeMin & Max value
1.byte1 byte-128 to 127
2.short2 bytes-32768 to +32767
3.int4 bytes-2147483648 to +2147483647
4.long8 bytes-9223372036854775808 to +9223372036854775807 (or)
-9.2 x 10-18 to 9.2 x 1018
Ex: - byte r.no = 10(0 - literal)
Literal means the constant value being directly storing into
variable.
long x = 150L;
L means take that number forcibly as long integer to allot the
memory as user defined.
float data types: - They can handle numbers with decimal points.
Such numbers called floating data type.
Sub type: -
S. No.Data typeMemory sizeMin & Max value
1.(Single precision ) float4 bytes-3.4e38 to + 3.4e38
2.Double precision 8 bytes-1.7e308 to + 1.7e308
Q.) What is the difference between float and double? *****
Ans: -float can represents up to 7 digits after decimal point
accurately.
Double can represents up to 15 digits after decimal point
accurately.
Ex: - float PI = 3.142F; F represents forcing the JVM to take
the value as float because JVM defaultly takes any decimal values
as double.
Character data type: - It represents a single characters.
S. No.Data typeMemory SizeMin & Max value
1.Char2 bytes0 to 65535
Ex: - char ch = x;
ASCII American standard code for information interchange.
S. No.Data typeMemory SizeMin & Max value
1.char2 bytes0 to 65535
2.byte1 byte-128 to 127
3.short2 bytes-32768 to +32767
4.int4 bytes-2147483648 to +2147483647
5.long8 bytes-9223372036854775808 to +9223372036854775807 (or)
-9.2 x 10-18 to 9.2 x 1018
6.float4 bytes-3.4e38 to + 3.4e38
7.double8 bytes-1.7e308 to + 1.7e308
8.boolean1 bit0 or 1
Keyboard consists 114keys. Keyboard consists up to 200
characters only.
Q) What is Unicode? *****
Ans: -Unicode is specification that includes the alphabetic of
all international languages into java character set. Unicode uses 2
bytes to represent single character.
4. String data types: - String represents a group of characters.
Strings are objects of string class in java.
Ex: - String name Inet solv;
String str = new String (A String);
Boolean data type: - They store either true or false. It can
handle only two values.
Ex: - boolean response = true;
Complete list of Java keywords: -
abstractbooleanBreakbytecasecatch
charclassConstcontinuedefaultdo
doubleelseExtendsfinalfinallyfloat
for gotoIfimplementsImportinstanceof
intinterfaceLongnativenewpackage
privateprotectedPublicreturnshortstatic
strictfpsuperSwitchsynchronizedthisthrow
throwstransientTryvoidvolatilewhile
assert
Transient: - A value of an instance variable in a class will not
persistent when the object is stored, such an instance variable can
be specified as transient variable, indicating that its value need
not be saved when objects of its classes are put in persistence
storage or it prevents fields from ever being serialized. Transient
fields are always skipped when objects are serialized.
Transient variables arent appropriate for equals() and
hashCode() methods.
Note: - That the transient modifier cannot be specified for
static variables as these do not belong to objects.
Volatile: - In multithreading environment, threads might cache
the values of member variable for efficiency reason. Since threads
can share a variable, it is then vital that reading & writing
of the value in the copies and the master variable do not result in
any inconsistency. As these variables values could be changed
unexpectedly. The volatile modifier can be used to inform the
compiler that it should not attempt to perform optimization on the
variable.
instanceOf: - The instanceof operator is used for object
reference variables only, and you can use it to check whether an
object is of a particular type. By type, we mean class or
interface-in other words, if the object referred to by the variable
on the left side of the operator passes the IS-A test for the class
or interface type on the rightside. Even if the object being tested
is not an actual instantiation of the class type on the right side
of the operator, instanceof will still return true if the object
being compared is assignment compatible with the type on the
right.
class A
{
public static void main (String [] args)
{
String s = new String("foo");
if (s instanceof String) {
System.out.print("s is a String");
}
}Operator: - An operator is a symbol that represents an
operation. `
a + b
(( a, b are operands, + is the operator)
Operand: - An operand is a variable on which operator acts
upon.
An operator may act upon a single operand. It is called unary
operator. If an operator acts upon two operands is called binary
operand. If an operator acts on three operands is called ternary
operand.
Operators in Java: -
1. Arithmetic Operators: -
+ - * / %
2. Unary Operators: -
- ++ --3. Assignment Operators: -
= += -= *= /= %=
4. Relational Operators: -
===!=
5. Logical Operators: -
&&||!
6. Boolean Operators: -
& |!
7. Bitwise Operator: -
a) Bitwise Compliment: -~
b) Bitwise and: -
&
c) Bitwise or: -
|
d) Bitwise xor: -
^
e) Bitwise left shift
>
8. Ternary Operator (Conditional Operator): -?:
9. Dot Operator (.): -
a) To refer a class in a package: -java.util.Date
b) To refer a method in class: - math.pow()emp.getsal()
c) To refer a variable in a class: -Employee.name, emp.name
10. Instanceof Operator: - To test whether an object belongs to
a class.
Ex: - emp instanceof Employee.
Arithmetic Operators: - These operators perform basic arithmetic
calculations like addition, subtraction, etc
Ex: - a = 13, b = 5
S. No.OperatorMeaningExampleResult
1.+Additiona + b18
2.-Subtractiona b8
3.*Multiplicationa * b65
4./Divisiona/b2.6
5.%Modulus operator (Remainder of division)a% b3
Unary Operators or Unary minus (-) Operator: - This operator
negates the value of a variable. (Negation means converting value
into + value vice versa).
Ex: - int x = -5;
System.out.printlin(x);
-5
System.out.printlin(-x);
5
System.out.printlin(-(-x));
-5
System.out.printlin(-(-(-x)));
-5
Increment Operator (++): - This operator increases the value of
a variable by one.
Ex: - int x = 1;
++x (2
x++ ( 3
x = x + 1 ( 4
Writing ++ before a variable name is called pre incrementation.
Writing ++ after a variable name is called post incrementation.
In pre incrementation, incrementation is done first any other
task is done next.
In post incrementation any other task is done first,
incrementation is done at the end.
Ex. 1: - int x = 1;
int x = 1;
S.o.println(x);
S.o.println(x)
S.o.println(++x);
S.0.println(x++);
S.o.println(x);
S.o.println(x);
Output
Output1 1
2 1
2
2
Ex. 2: -a = 1;
a = 1;
b = 2;
b = 2;
a = ++b;
a = b++;
a = 3
a = 2
b = 3
b = 3
Ex 3: - What is the value of the following expression, if a =
7?
++a*a++;
[ b]
a) 49
b) 64
c) 56
d) 72
e) None of these
Decrement Operator (--): - This operator decreases the value of
a variable by one.
int x = 1;
--x ( 0
x-- ( -1
x = x 1 ( - 2
Writing before a variable is called pre decrementation, writing
after a variable is called post decrementation.
Assignment Operator (=): -
1. It is used to store a value into a variable.
Ex: - int x = 15;2. It can store the value of variable into
another variable.
Ex: - int y = x;
3. It can store the value of an expression into a variable.
Ex: - int z = x + y 10;
Note: - At the left hand side of assignment we should use only
one variable.
Compact Notation: -
a = a + 10 ( a +=10
b = b 100(b -=10
j = k * j(j *=k
i = i/10;(i/=10
p = p%10( p%=10
Relational Operators: - These operators are useful to compare
two quantities. They are used to constant conditions.
> < >=b)..;
if(a==100);
if(x!=y)...;
Logical Operators: - These operators are useful to combine more
than one condition. Combining more than one condition called
Compound condition.
&& - and|| = or
! - not
Ex: - if(a>b && b>c)...;
if(a==100||b=50)...;
if(!(x==1));
Boolean Operator: - These operators act upon Boolean variables
and they return Boolean value.
&-Boolean and
|-Boolean or
boolean a = true;
boolean b = false;
a & b- false
a & a- true
b | b- false
!a- false
!b- true
Bitwise Operators: - These operators act upon individual bits of
a number.
Convert 45 into binary: - Divide the number successively by 2
and table remainders from bottom to top.
45
0 0 1 0 1 1 0 1
22 1
11 0
5 1
2 1
1 0
0 1
Converting 00101101 into decimal: - Multiply the bits by the
powers of 2 & take the sum of those products.
00101101
xxxxxxxx
27 +26 +25 +24 +23 +22 +21 +20
0 +0 +32 +0 +8 +0 +0 +1 = 45
Bitwise Compliment (~): - This operator gives complement from of
a number.
Ex: - int x = 10;
~x = -11;
Bitwise and (&): - This operator performs anding operations
on individual bits
aba & bThis table is called truth table. It means, it
shows
00 0
input and output bits
01 1
10 0
11 1
Ex: - x = 10 y = 11, x & y =?
x = 00001010
y=00001011
x & y=00001010 = 10
Bitwise or (|): - This operator performs or-ing operations on
individual bits
aba | b
00 0
01 1
10 1
11 1
Ex: - x = 10 y = 11, x | y =?
x = 00001010
y=00001011
x | y=00001011 = 11
Bitwise Xor (^): - ^ is called as Circum flex or Cap or caret.
This operator performs exclusively oring operations on individual
bits
aba | b
00 0
01 1
10 1
11 0
Ex: - x = 10 y = 11, x ^ y =?
x = 00001010
y=00001011
x ^ y=00000001 = 1
Bitwise left shift (2
x >> 2
x = 1000001010
x >> 200000010 = 2
Bitwise zero fill right shift (>>>): -
Q) What is the difference >> and >>>? *****
Ans: ->> shifts the bits towards right and also preserves
the sign bit (0 for positive and 1 for negative sign).
>>> also shifts the bits towards right but does not
preserve the sign bit. It always fills the sign bit with 0. For
this reason it is called zero fill right shift.
Ex: - //Bitwise operators
class Bits{
public static void main (String args[ ]){
byte x,y;
x = 10;
y = 11;
System.out.println(~x = +(~x));
System.out.println(x & y = +(x&y));
System.out.println(x | y = +(x|y));
System.out.println(x ^ y = +(x^y));
System.out.println(x >y));
}
}
Ternary Operator: - This operator acts on three variables i.e.
it will takes three variables.
This operator works like a conditional if-else statement. So
this operator is called as conditional operator.
Syntax: -
var = exp1?exp2:exp;
max = (a>b)?a : b;
(or)if(a>b)
max = a;
else
max = b;
dot (.) operator: -
1. packagename.classname (to refer classname)
java.io.BufferedReader
2. classname.var or objectname.var (to refer variable)
System.outemp.name
3. classname.method() or objectname.method() (to refer
method)]
Math.sqrt()
br.read
instanceOf operator: - It is denoted as instanceof. It is used
to test whether the object belongs to that class or not.
Syntax: - objectname instanceof classname
Ex: - br instanceof BufferedReader
This operator returns true of false i.e Boolean values.
Executing the statements one by one by JVM is called sequential
execution. In sequential execution programmers does not have better
control on the flow of execution.
In Random execution the programmer can executive any statement
directly or repeatedly. This gives better control for the
programmer on the flow of execution.
Random execution is possible by using control statements.
Control Statements: - Control statements modify the flow of
execution and give better control for the programmer on the flow of
execution. Without control statements programmers can not able to
write better programs.
1. ifelse statement
4. for loop
7. continue statement
2. do.while loop
5. switch statement
8. return statement
3. while loop
6. break statement
A loop can be executed repeatedly. A statement can be executed
once only.
Ifelse statement: - This statement performs a task (one or more
statement) depending upon whether a condition is true or not.
Syntax1: - if(condition)
statement1;
[else statement2;]
Ex: - //Test if a given number is +ve or ve
class Demo
{
public static void main (String args[ ])
{
int x;
x = -15;
if(x==0)
System.out.println(It is zero);
else if(x>0)
System.out.println(x+ is positive);
else
System.out.println(x+ is negative);
}
}
C:\rnr\javac Demo.java(C:\rnr\java Demo(Output: - -15 is
negative.
Syntax 2: -
if(condition1)
if(condition2)
if(condition3)
statement1;
else statement2;
else statement3;
else statement4;
Dowhile loop: - This loop repeatedly executes a group of
statements as long as a given condition is true.
Storing starting value into the variable is called
initialization.
Syntax: -do
{
statements;
}while(condition);
Ex: - //To display numbers from 1 to 10
Class Demo
{
public static void main(Static args[ ])
{
int n = 1;
do{
System.out.println(n+ );
n++;
}while(n