0% found this document useful (0 votes)
2 views

JAVA Unit-1

This document provides an introduction to object-oriented programming with a focus on Java, detailing its features, types of applications, and history. It explains the differences between JDK, JRE, and JVM, as well as Java's architecture and variable types. Additionally, it covers data types in Java, including primitive and non-primitive types, along with examples of variable declaration and initialization.

Uploaded by

deoreg1386
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA Unit-1

This document provides an introduction to object-oriented programming with a focus on Java, detailing its features, types of applications, and history. It explains the differences between JDK, JRE, and JVM, as well as Java's architecture and variable types. Additionally, it covers data types in Java, including primitive and non-primitive types, along with examples of variable declaration and initialization.

Uploaded by

deoreg1386
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit-1

Introduction to object-oriented programming Features of object-oriented


programming, data types, variables, literals, operators, constants, identifiers.
INTRODUCTION
• Java is a programming language and a platform.

• Platform Any hardware or software environment in which a program runs, known as a platform. Since Java has its own Runtime Environment
(JRE) and API, it is called platform.

• According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of them are as follows:

 Desktop Applications such as acrobat reader, media player, antivirus etc.

 Web Applications such as irctc.co.in, javatpoint.com etc.

 Enterprise Applications such as banking applications.

 Mobile

 Embedded System

 Smart Card

 Robotics

 Games etc.
TYPES OF JAVA APPLICATIONS
1) Standalone Application
It is also known as desktop application or window-based application. An application that
we need to install on every machine such as media player, antivirus etc. AWT and Swing are
used in java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used
for creating mobile applications.
History of Java
• 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
describes 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) Why Oak? 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 they choosed 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).
FEATURES OF JAVA OR BUZZWORDS
• Simple
• Object-Oriented
• Platform independent
• Secured
• Robust
• Architecture neutral
• Portable
• Dynamic
• Interpreted
• High Performance
• Multithreaded
• Distributed
Simple Object-oriented
• According to Sun, Java language is simple because: • Object-oriented means we organize our software
as a combination of different types of objects that
• syntax is based on C++ (so easier for programmers incorporates both data and behavior.
to learn it after C++).
• Object-oriented programming(OOPs) is a
• removed many confusing and/or rarely-used methodology that simplify software development
features e.g., explicit pointers, operator and maintenance by providing some rules
overloading etc.
• Basic concepts of OOPs are:
• No need to remove unreferenced objects because
there is Automatic Garbage Collection in java.  Object
 Class
Robust  Inheritance
• Robust simply means strong.  Polymorphism
• Java uses strong memory management.  Abstraction
• There are lack of pointers that avoids security  Encapsulation
problem.
• There is automatic garbage collection in java.
• There is exception handling and type checking
mechanism in java.
• All these points makes java robust.
Platform Independent
• A platform is the hardware or software environment in which a program
runs.
• There are two types of platforms software-based and hardware-based.
• Java provides software-based platform. The Java platform differs from
most other platforms in the sense that it's a software-based platform that
runs on top of other hardware-based platforms.
• It has two components:
Runtime Environment
API(Application Programming Interface)
• Java code can be run on multiple platforms e.g. Windows, Linux,Sun
Solaris, Mac/OS etc.
• Java code is compiled by the compiler and converted into bytecode which
is WORA i.e. Write Once and Run Anywhere(WORA).
Distributed
Architecture-neutral
We can create distributed applications in java.
• There is no implementation dependent RMI and EJB are used for creating distributed
features e.g. size of primitive types is set. applications.
We may access files by calling the methods
Portable from any machine on the internet.
• We may carry the java bytecode to any
platform. Multi-threaded
A thread is like a separate program, executing
High-performance concurrently.
• Java is faster than traditional We can write Java programs that deal with
interpretation since byte code is "close" many tasks at once by defining multiple
to native code still somewhat slower than threads.
a compiled language (e.g., C++) The main advantage of multi-threading is that
it shares the same memory.
Threads are important for multi-media, Web
applications etc.
Simple Program of Java
• class keyword is used to declare a class in java.
import java.lang.*; • public keyword is an access modifier which represents
visibility, it means it is visible to all.
import java.io.*; • static is a keyword, if we declare any method as static,
class Simple{ it is known as static method.
public static void main(String args[]){ • The core advantage of static method is that there is no
need to create object to invoke the static method.
System.out.println("Hello Java");
• The main method is executed by the JVM, so it doesn't
} require to create object to invoke the main method. So
} it saves memory.
• void is the return type of the method, it means it
doesn't return any value.
• save this file as Simple.java
• main represents startup of the program.
• To compile: javac Simple.java
• String[] args is used for command line argument. We
• To execute: java Simple will learn it later.
• System.out.println() is used print statement. We will
learn about the internal working of System.out.println
statement later.
What happens at runtime?
What happens at compile time
DIFFERENCE BETWEEN JDK, JRE AND JVM
• JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides
runtime environment in which java bytecode
can be executed.
• 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 JVM
uses at runtime. Implementation of JVMs are
also actively released by other companies
besides Sun Micro Systems.
• JDK is an acronym for Java Development Kit. It
physically exists. It contains JRE + development
tools.
INTERNAL ARCHITECTURE OF JVM
• Class loader is a subsystem of JVM that is used to load class files.
• Class(Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.
• Heap: It is the runtime data area in which objects are allocated.
• Java Stack stores frames. It holds local variables and partial results, and plays a part
in method invocation and return
• PC (program counter) register: It contains the address of the Java virtual machine
instruction currently being executed.
• Native Method Stack: It contains all the native methods used in the application.
• Execution Engine: It contains:
1) A virtual processor
2) Interpreter: Read bytecode stream then execute the instructions.
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.
Variables in Java • Variable Initialization in Java
• A variable in Java is a container that 1. Static:
holds the value during the execution of When the class is loaded into the memory, the
Java program. memory is determined for the variables. Such
variables are known as static variables or class
variables in java.

static String name = "Kiran";

2. Dynamic: In dynamic initialization, we can


declare variables anywhere in the program.
When the statement will execute, JVM assigns
the memory to them.
char ch = 'B'; // Declaring and initializing
character variables.
• Variable Declaration in Java
int number = 100; // Declaring and initializing
1. data_type variable_name; integer variables.
2. data_type variable_name = value; int time = 40, distance = 50;
Naming Convention to Declare Variables in Java
1. As per Java coding standard, the variable name should start with a lower case letter. int
age;
2. If you have lengthy variables such as more than one words then you can declare the first
word small and second word with the capital letter like this: int smallNumber;
3. The variable name should not contain a blank space.
int num ber = 100;
4. The variable name can begin with a special character such as $ and _. For examples:
String $name; // valid.
String _nSchool; // valid.
int @num; // invalid.
5. The first character must be a letter. For example, int 2num; // invalid.
6. We should not use java keywords as a variable name.
7. The variable names are case sensitive in Java.
Types of Variables in Java
There are three types of variables in java
local variable: A variable that is declared inside the method is called local
variable
instance variable: A variable that is declared inside the class but outside
the method is called instance variable . It is not declared as static
static variable: A variable that is declared as static is called static variable.
It cannot be local.
class A{

int data=50;//instance variable

static int m=100;//static variable

void method(){
int n=90;//local variable
}

}//end of class
Example int totalMarks = cMarks + pMarks + mMarks;
public class Student System.out.println("Total marks in PCM: " +totalMarks);
{ }

// Declaration of constructor. public static void main(String[] args)


Student() {
{ // Create an object of class.
Student s = new Student();
String nCollege = "PIET"; // local variable.
System.out.println("Name of college: " +nCollege); // // This statement will produce compile-time error because
We can access local variable inside the constructor. local variable cannot be accessed from the outside.
} // System.out.println("Name of college: " +nCollege);

// Declaration of instance method. s.subMarks(); // Calling instance method.


void subMarks() // System.out.println("Total marks in PCM: " + totalMarks);
// Compile-time error.
{
}
// Declaration and initialization of local variables. }
int cMarks = 90; int pMarks = 85; int mMarks = 99;
Data Types in Java
• Primitive Data types in Java
In java, there are two types of data types • Primitive data types in Java are those data types
• primitive data types whose variables can store only one value at a
time.
• non-primitive data types • These data types are pre-defined in Java. They
are named by a Keyword and
• Primitive data types are not user-defined data-
types.
• For example:
int x; // valid
x = 10; // valid because "x" store only one value
at a time because it is the primitive type variable.
x = 10, 20 ,30 40; // invalid.
Types of Primitive data types in Java
• Java defines eight primitive data • Size of Data Types in Java
types: boolean, char, byte, short, int,
long, char, float, and double.
• We can further categorize these into
Data Type Default Value Default size Range in signed
boolean false 1 bit True or false

four groups as: char


byte
'\u0000'
0
2 byte
1 byte
0 to 65536
-128 127

• Conditional category data type: short 0 2 byte -32768 32767

boolean int 0 4 byte -2,147,483,648 to 2,147,483,647


9,223,372,036,854,775,80

• Character category data type: char long 0L 8 byte -9,223,372,036,854,775,808


7

• Integer category data types: byte,


float 0.0f 4 byte 3.4e-038 3.4e+038

double 0.0d 8 byte 1.7e-308 1.7e+308


short, int, and long.
• Float category data types: float and
double
• Integer data types in Java
Example
public class Test {
// Declare a variable of type int.
int x; • Java Floating-Point Data Types
public static void main(String[] args)
{
// Create an object of class.
Test t = new Test();
System.out.println("Default value of x: " +
t.x);
} • Character Data type : store a single
character
} • Boolean Data type: one bit of
information as either true or false.
Example for integer data type
public class ByteExample int lightSpeed;
{ long days;
public static void main(String[] args) long seconds;
{ long distance;
byte num = 100; // Speed of light in miles per sec.
System.out.println(num); lightSpeed = 186282;
short num = 200; days = 1000;
System.out.println(num); // Number of days.
int a = 200; seconds = days*24*60*60; // Convert into seconds.
int b = 300; distance = lightSpeed * seconds;
System.out.println(a+b); System.out.println("In 1000 days, distance traveled by
light: " +distance + " miles");
}
}
Example for float data type Example for character data type

public class CharExample {


public class Area { public static void main(String[] args)
public static void main(String[] args) {
{ char ch1, ch2;
double pi = 3.1416; ch1 = 88;
float r = 5.5f; // Radius of circle. ch2 = 'R';
char ch3;
// Calculate the area of circle. ch3 = 'A';
double area = pi * r * r;
System.out.println("Area of circle: " +area); ch3++;
} System.out.println(ch1);
} System.out.println(ch2);
System.out.println(ch3);
}
}
Example for Boolean data type
public class DefaultExample
{
// Declaration of instance Variables.
int a; • Why take boolean data types zero bytes of
char b;
memory?
float c;
boolean d;
• Boolean data type takes zero bytes of
// Static method or main method.
memory space because boolean data type in
public static void main(String[] args) Java is implemented by Sun Micro System
{ using the concept of a flip-flop.
// Create the object of the class.
• A flip-flop is a general-purpose register that
DefaultExample obj = new DefaultExample();
stores one bit of information (one for true
// Call the variable and print it. and zero for false).
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Non-Primitive Data types in Java with Example
• Non-primitive data types are created by • create an object of a class using new keyword.
programmers.
• For example,
• They are not predefined in Java like primitive data
types. sc = new School();
• These data types are used to store a group of School sc = new School();
values or several values. School ➞ name of the class.
• In reference data types, an object reference sc ➞ Object reference.
variable ( or simply called reference variable)
An object reference is a variable that stores the
• School sc; address of an object in the computer’s memory.
• Here, School is the name of a class, and “sc” is the An object represents an instance through which
name of a reference variable we can access a member.

School() ➞ Constructor of the class.


The constructor of a class is generally used to
initialize an object.
new ➞ is a special keyword that creates the
memory in java.
Example
public class School
{ Memory Allocation of Object & Object Reference Variable
// Declaration of a primitive variable.
String name = “SRI"; // Instance variable.

public static void main(String[] args)


{
// Creating an object of the class.
School sc = new School(); // sc is Non-primitive data type, i.e. Object
REFERENCE.
// Print the address of the memory location of an Object.
System.out.println(sc);

// Now we cannot access instance variable directly.


// We call instance variable by using reference variable sc which is created
above.
System.out.println(sc.name);
}
}
Types of Reference Data types in Java
• Class and objects: Every class is data type and it is also considered as user-defined
data types. This is because a user creates a class. For more details: Class and objects in java
• String: A string represents a sequence of characters like India, ABC123, etc.
 The simplest way to create a string object is by storing sequence of characters into
string type variable like this:
 String str = “Universe”;
 Here, string type variable str contains “Universe”. A string is also a class. For more
details: String in Java.
• Array: An array in java is an object which is used to store multiple variables of the same
type. These variables can be primitive or non-primitive data types.
 The example of declaring an array variable of primitive data type int is as follows:
 int [ ] scores;
 The example of declaring an array variable of non-primitive data type is
 Student [ ] students; // Student is a name of class.
• Interface: An interface is declared like a class but the only difference is that it contains
only final variables and method declarations. It is a fully abstract class.
Memory Allocation of Primitive, Non-primitive Data Types
Constants in Java
• Integer Constants in Java
• Decimal integer
• Octal integer
• Hexadecimal integer

public class IntegerConst {


public static void main(String[] args)
{
int a, b, c;
a = 20; // decimal notation.
b = 020; // octal notation.
c = 0x20F; // hexadecimal notation.

System.out.println("Decimal notation 20: " +a);


System.out.println("Octal notation 020: " +b);
System.out.println("Hexadecimal notation 0x20F: " +c);
}
}
Real (Floating-point) Constants in Java

Real constants consist of a sequence of • Single Character Constants in Java


digits with fractional parts or decimal • A single character constant ( or simply
points. character constant) is a single character
These constants are also called floating- enclosed within a pair of single quote.
point constants. • The example of single-character constants
The valid examples of real constants are are as follows:‘5’ ‘x’ ‘;’
2.3, 0.0034, -0.75, 56.7, etc. • String Constants
A real constant number can also be • A string constant is a sequence of
expressed in exponential or scientific characters within a pair of double-quotes.
notation. • The characters can be alphabets, special
For example, the value 235.569 can also be characters, digits, and blank spaces.
written as 2.35569e2 in exponential • The valid examples of string constants are
notation. given below: “Hello Java”
mantissa e exponent “1924” “?…!” “2+7” “X” etc.
• Backslash Character Constants

Constants Meaning
‘b‘ back space
‘f‘ form feed
‘n‘ new line
‘r‘ carriage return
‘t‘ horizontal tab
‘‘‘ single quote
‘”‘ double quote
‘ ‘ backslash
Operators in Java • Classification of Operators based on
Symbols and Named in Java

1. Symbolic operator in Java


Arithmetic operators: +, -, *, /, etc.
Relational operators: <, >, <=, >=, = =, !=.
Logical operators: &&, ||, !.
1. Unary operator: The operator that acts on a single
operand is called unary operator. A unary operator Assignment operators: =,
uses a single variable. Increment and decrement operators: ++, – –
2. Binary operator: The operator that acts on two Conditional operators: ?:
operands is called binary operator. A binary operator
uses two variables. Bitwise operators: &, !, ^, ~, <<, >>, >>>
Shift operators: <<, >>, >>>.
3. Ternary operator: The operator that acts on three
operands is called ternary operator. A ternary
operator uses three variables.
Example public class MixedTest
public class MyTest {
{ int x = 20; // Integer
int x = 9; double y = 12.5; // Real
int y = 12;
int z = 3; void div()
void m1() { {
int exp1 = x - y / 3 + z * 2 - 1; double z = x/y;
System.out.println("Evaluation1 = " +exp1); } System.out.println("z = " +z);
void m2() { }
int exp2 = (x - y)/3 + ((z * 2) - 1); public static void main(String[] args)
System.out.println("Evaluation2 = " +exp2); } {
public static void main(String[] args) { MixedTest mt = new MixedTest();
MyTest t = new MyTest(); mt.div();
t.m1(); // Calling of m1 method. }
t.m2(); // Calling of m2 method. } }
}
Relational Operators Logical operators

Operators Meaning Description Operators Meaning


This operator checks whether the value of the left
operand is less than the value of the right 1. && AND operator
1. < Less than operand. If the value on the left side of operator
is less than the value on the right side, the result 2. || OR operator
becomes true.
3. ! NOT operator
This operator evaluates that the value of the left
operand is less than or equal to the value of the
2. <= Less than or equal to
right operand. If it is the case, the operator
returns true.
This operator evaluates that the value of the left
operand is greater than the value of the right Assignment Operator
3. > Greater than operand. If the value on left side of operator is
greater than the value on right side, the greater
than (>) operator returns true.
Simple Assignment : v = expression;
This operator tests that the value of the left Compound Assignment: v op = expression;
operand is greater than or equal to the value of
Greater than or equal
4. >=
to
the right operand. If the value on the left side of
the operator is greater than or equal to the value Assignment as Expression: int x = y – z + 4;
on the right side, then the operator returns true.

This operator evaluates that the value of left and


right operands are equal or not. If values on both
5. == Equal to
sides of the operator are equal to each other, the
equal operator (==) returns true.
This operator evaluates that the left operand is
not equal to the right side. If the values on both
6. != Not equal to
sides of operator are not equal to each other, the
not equal operator returns true.
• Unary Operator public class PreInr {
The operator that acts on a single public static void main(String[] args) {
operand i.e. int x = -10; int x = 2;
• Types of Unary Operators int y = ++x;
Unary minus operator ( – ) System.out.println("x = " +x+ ", " +"y = " +y);
int x = 5; }}
x = -5;
Increment operator ( ++ )
public class PostInr {
Pre-increment Operator ++x; public static void main(String[] args)
Post increment Operator x++; {
int x = 2;
Decrement operator ( – – ) int y = x++;
Pre-decrement Operator System.out.println("x = " +x+ ", " +"y = " +y);
}
Post-decrement Operator }
• Conditional operator provides a • Bitwise Operator
one-line approach for creating a
simple conditional statement. • An operator that acts on individual
bits (0 or 1) of the operands is
• The conditional operator (?:) is also called bitwise operator in Java.
known as ternary operator because
it takes three operands and perform Operator Meaning
a conditional test. 1. & bitwise AND (Binary)

variable = exp1 ? exp2 : exp3; 2. | bitwise OR (Binary)


3. ^ bitwise exclusive OR (Binary)
where exp1, exp2, and exp3 are
expressions. 4. ~ bitwise NOT (Unary)
5. << shift left
6. >> shift right
7. >>> unsigned right shift
Bitwise NOT

A ~A
0 1
1 0

Shift Operator
Left Shift Operator

Right Shift Operator


1. Signed right shift operator (>>)
2. Unsigned right shift operator (>>>)

You might also like