BSc Java unit 1
Java is a simple object-oriented programming language developed by James Gosling, Patrick
Naughton and Mike Sheridan in the year 1991.
This language was initially called as “Oak”, and renamed as “Java” in 1995.
Q) Java Essentials
java is the platform independent, object-oriented programming language. Java contains the
following features.
1)High level language:
Java is a high-level language that looks very similar to C and C++, but offers many unique
features of its own.
2)Java byte code:
Byte code is an intermediate code generated by compiler, such as Javac.
3)Java virtual machine:
JVM acts as an interpreter which takes byte code and convert it into machine code and execute
it.
Java Source Code
Java Byte Code
JVM
Q) Java Virtual Machine (JVM)
The JVM is responsible for interpreting byte code and translate this byte code into binary form
which is understandable by the system.
The Java virtual machine is not machine specific.
JVM is a part of Java Run Time Environment (JRE).
It is a specification that provides runtime environment in which java byte code can be
executed.
BSc Java unit 1
Q) Java Features
The features of java are:
1)Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. Java language
is a simple programming language because:
o Java syntax is based on C++.
o Java has removed many complicated features like explicit pointers, operator overloading,
etc.
o There is no need to remove unused objects because there is an Automatic Garbage
Collection in Java.
2)Object-oriented:
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
combine both data and behavior.
3)Platform Independent:
Java is platform independent language because Java is a write once, run anywhere (WORA)
language. A platform is the hardware or software environment in which a program runs.
Java code can be executed on multiple platforms, for example, 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).
4)Compiled and interpreted: Java incorporates both interpretation and compilation. So, Java is
a two-stage system.
BSc Java unit 1
Class Loader: Class Loader in Java is a part of Java runtime environment, which is used
to dynamically load Java Classes into JVM.
Byte Code verifier: It verifies the code and ensures that the code is fit to execute by JVM.
5)Secured
Java has best feature called security. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
6)Robust
Java is robust (strong)because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
6)Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
7)Portable
Java is portable because it provides to carry the Java bytecode to any platform. It doesn't require
any implementation.
8)Distribute
Java is distributed because it facilitates users to create distributed applications in Java. This
feature of Java makes us able to access files by calling the methods from any machine on the
internet
9)Multi-threaded
Multi-threading: Multi-threading in Java is a process of executing multiple threads
simultaneously; this means that we need not wait for the application to finish one task before
beginning the other. Java multi-threading is mostly used in Games, Animation etc.
10)Automatic memory management:
Automatic garbage collection is handled by JVM. Java automatically removes the objects that
no longer need.
Q) Creation and execution of java program
The Simple way to create, compile, and run a Java program is to use an ordinary text editor to
create a file called [Link]. Here are the contents of the file:
BSc Java unit 1
Program:
public class Demo
{
public static void main(String args[ ])
{
[Link]("Hello World");
}
}
This is a Java class declaration. The name of the class is Demo. This means the name of the
file must be [Link]. Note that Java is [Link] order to execute a class from the
command prompt, the class must contain a public static method called main.
Compiling
From a command prompt, type the command as:
E:/javac [Link]
Running
Next, type the command:
E:/java Demo
java is the name of the Java Virtual Machine (JVM). A virtual machine is a computer
implemented in software.
Q) Data types in java
Data types: Data type specifies the type of the data that is to be stored in a variable.
BSc Java unit 1
Data Size Description
Type
byte 1 byte Stores whole numbers from -128 to 127
short 2 Stores whole numbers from -32,768 to 32,767
bytes
int 4 Stores whole numbers from -2,147,483,648 to 2,147,483,647
bytes
long 8 Stores whole numbers from -9,223,372,036,854,775,808 to
bytes 9,223,372,036,854,775,807
float 4 Stores fractional numbers.
bytes Sufficient for storing 6 to 7 decimal digits
double 8 Stores fractional numbers.
bytes Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 Stores a single character
bytes
1)Primitive Data Types:
Primitive data types are of two types in Java: numeric and non-numeric
1)Numeric: It is divided into two groups:
a) Integer types stores whole numbers, positive or negative without decimals. They
are byte, short, int and long.
b) Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.
2)Non-Numeric:
It is divided into two types
a) Boolean: A Boolean data type is declared with the Boolean keyword and can only take the
values true or false:
Boolean values are mostly used for conditional testing.
b) Characters: The char data type is used to store a single character. The character must be
enclosed in single quotes, like 'A' or 'c':
2) Non primitive data types: They are 3 types:
BSc Java unit 1
a) Strings: The String data type is used to store group of characters (text). String values must be
enclosed in double quotes:
Example
"Hello World";
b) class: A class is a collection of objects.
c) Array: An array is a collection of homogeneous elements.
Q) Structure of Java Program
A typical structure of a Java program contains the following elements
● Package declaration
● Import statements
● Comments
● Class definition
● Class variables, Local variables
● Methods/Behaviors
Package declaration
A class in Java can be placed in different directories/packages based on the module they are
used.
Import statements
The import statement is used to declare the classes to use in our class. If the classes we use are
in the same package as our class, we may not need to declare the import statement for these
classes.
Comments :The comments in Java can be used to provide information about the variable,
method, class or any other statement. It can also be used to hide the program code for a specific
time.
Class Definition
A name should be given to a class in a java file. This name is used while creating an object of a
class, in other classes/programs.
Variables
The Variables are used to identify the memory location and holds the value.
Main Method :Execution of a Java application starts from the main method. In other words, it’s
an entry point for the class or program that starts in Java Run-time.
Q) Type Casting
BSc Java unit 1
Type conversion: In java type conversions are performed automatically when the type of the
expression on the right-hand side of assignment operator can be safely promoted to the type of
the expression on the left-hand side.
byte->short->int-> long-> float->double (widening conversion)
ex:
byte b=10;
int i= b;
type casting: The process of converting one data type to another is called casting. Casting is
also known as narrowing conversion
byte<-short<-int<- long<- float<-double (narrow conversion)
syntax:
type variable1 = (type) variable2
ex:
int i= int(8.0/2.0)
Q) Java Operators:
Operators are used to perform an operation on operands. Java
supports the following types of operators:
1)Arithmetic Operators: Arithmetic Operators are used to perform mathematical
operations like addition, subtraction, etc
Operator Example
+ Addition A+B
– Subtraction A-B
*Multiplication A*B
/ Division A/B
% Modulus A%B
example:
class A
{
public static void main(String args[ ])
{
int a=10, b=20;
[Link](a+b);
}
}
2)Assignment Operator: An Assignment Operator is an operator used to assign anew value to a
variable
ex: y=10
class Assignment
BSc Java unit 1
{
public static void main(String args[ ])
{
int a=10;
[Link](a);
}
}
3) Relational Operators in Java: These operators are used to do the comparison
between any two quantities.
Operator
==
!=
>
<
>=
<=
Example
class A
{
public static void main(String args[ ])
{
int a=10,b=20;
[Link](a<b);
}
}
4)Logical Operators: These are used to check more than one condition by combining two or
more relations
Operator Description
&&(and) True if both the operands is true
|| (or) True if either of the operands is true
! (not) True if an operand is false (complements the operand)
class Logical
{
public static void main(String args[ ])
{
int a = 10;
int b=20;
[Link](a<b && b>a); 10<20 && 20>
BSc Java unit 1
}
}
5)Unary Operator: Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.
++ : increment
-- : decrement
class unary
{
public static void main(String args[ ])
{
int a = 10, b,c;
b=++a;
[Link](a);
[Link](b);
c=a++;
[Link](a);
[Link](c);
}
}
6)Bitwise Operator: Bitwise operations directly manipulate bits. In all computers,
numbers are represented with bits, a series of zeros and ones.
Operator Example
& (AND) a&b
| (OR) a|b
^ (XOR) a^b
7) Ternary Operators: The ternary operator is also called as conditional operator. It
performs operations on three operands. It evaluates the condition, if condition is
true the statement1 is executed otherwise statement2 is executed
Syntax:
Condition)? (Statement1): (Statement2);
class Ternary
{
public static void main (String args[ ])
{
int a = 20, b = 10, c;
c = (a>b)? a: b
[Link](c);
}
}
BSc Java unit 1
Q) Java Conditional Statements
1) The if Statement :The if statement is used to execute a block of Java code if a condition
is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
program
class A
{
public static void main(string args[ ])
{
int x = 20;
int y = 18;
if (x > y)
{
[Link]("x is greater than y");
}
[Link](“completed”);
}
}
2) The if else Statement: The if else statement is used to execute a block of code if the condition
is true otherwise else block will be executed.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
program
class A
{
public static void main(string args[ ])
{
int a=10,b=20;
if (a>b)
{
[Link](“a”);
}
else
BSc Java unit 1
{
[Link]("b");
}
}
}
3) Java Switch Statements: The switch statement is used to select one of many code blocks to
be executed.
Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The switch expression is evaluated once. The value of the expression is compared with the
values of each case. If there is a match, the related block of code is executed.
program
class A
{
public static void main(String args[ ])
int day = 4;
switch (day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
default:
[Link](“no match found”);
}
BSc Java unit 1
Q) Loops
The purpose of loop statements is to execute Java statements many times until the specified
condition is satisfied.
1)While Loop
The while loop is used to repeatedly execute a block of code based on a given condition true.
The condition will be evaluated before the iteration starts.
Syntax
while (condition)
{
// code block to be executed
}
program
class A
{
public static void main(String args[])
{
int i = 0;
while (i < 5)
{
[Link](i);
i++;
}
}
}
2)The Do While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do
{
// code block to be executed
}
while (condition);
The loop will always be executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
Example
class A
{
public static void main(String args[ ])
{
int i=0;
BSc Java unit 1
do
{
[Link](i);
i++;
}
while (i < 5);
}
}
3)for loop : When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop:
Syntax
for (initialization; condition; increment/decrement)
{
// code block to be executed
}
program
class A
{
public static void main(String args[ ])
{
for (int i = 0; i < 5; i++)
{
[Link](i);
}
}
}
4)for each loop: Java foreach loop, also called Enhanced for loop. This feature helps us to
retrieve the elements of an array rather than using array index.
Syntax
for (datatype var: array)
{
...
}
Here, array - array name
var - each element of array assigned to a variable
program
class A
{
public static void main (String args[ ])
{
int a[ ] = {3, 9, 5};
for (int n: a)
{
[Link](n);
BSc Java unit 1
}
}
}
Q) What is a class? How it is declared? How the variables of class declared?
class is user defined data type. A class is a collection of objects of similar type.
In java data members are called fields and member functions are called methods.
class declaration in java
class classname
{
field declaration;
method declaration;
}
class Body:
The class contain two different sections.
1)variable declaration(field): This describes the state of a class.
2)Method declaration: This describes the behavior of a class.
There are three types of variables in a class.
1)Local variable:
These are the variables declared inside the method.
2)Instance variables:
These are the variables that are declared inside the class and outside the methods.
3)static variables:
These are the variables that are declared inside the class using static keyword and written
outside the method. class variables are also called as static variables.
program
class A
{
int i=50; // instance variable
static int j=100; // static variable
void method ()
{
int k=90; //local variable
}
}
Q) What is an object? How to declare an object and how to initialize an object?
An object is defined as an instance of a class. An object is used to access the fields and methods
of a class.
Creating Objects:
BSc Java unit 1
Objects in java are created using the new operator.
syntax:
class-name object-name;
ex: Student s1; // creating an object or declaring an object.
Instantiating an object:
Rectangle rect1; // statement1
rect1=new Rectangle(); // statement2
(or)
Rectangle rect1=new Rectangle();
The first statement declares the variable to hold the object.
The second statement assigns the reference to the variable.
Initializing an object:
Each object will contain its own set of variables. We must have to access the class members
using dot(.) operator.
object name. variable name;
object name. method name (parameter list);
Action statement result
Declare null
Rectangle rect1; rect1
instantiation rect1=new Rectangle (); rect1
Rectangle Object
here rect1 is a reference to Rectangle object
Rectangle rect1= new Rectangle ();