Java Chap1
Java Chap1
Features of Java
- Simple:
Java is easy to learn and use.
Syntax is adopted from c++.
- Object Oriented:
Java is pure object oriented language
Everything in java is in form of classes and objects.
Object model in java is simple and easy to extend.
- Platform independent
A platform is hardware or software environment where program runs.
Java code is compiled by compiler and converted into byte code.
This byte code is platform independent because it can run in multiple platforms
like windows, linux,mac etc.
It follows principle write once run everywhere.
- Secured
Java is secured because no explicit pointer.
Java code runs inside jvm which prevents code from hacker.
Java system verifies all memory accesses.
- Robust
Java makes an effort to eliminate codes with error using compile and run time
checking.
Java has improved in memory management and mishandled exception.
- Architectural neutral
Java is not tied to a specific machine or operating system architecture.
Compiler generates bytecode which have nothing to do with particular computer
architecture, hence a java program is easy to interpret on any machine.
- Portable
Java program can execute in any environment where there is jvm.
Java program can run on any platform.
- Dynamic
Java program carries significant amount of runtime information which is used to
verify and resolve access to object at run time.
- Distributed
Java is designed for distributed environment of internet.
Multiple programmers at multiple locations can collaborate on same project.
- Multithreading
Thread is like separate program executing concurrently.
One can write java program that deals with many task at once by defining multiple
threads.
The main advantage of multithreading is it shares same memory.
- High performance
Java enables high perfomance with use of just in time compiler.
Class
- A class in java is a set of data members, constructors, methods.
- It is user defined data type.
- Class does not occupy memory.
Syntax
accessmodifier class classname
{
data-type instance-variable1;
data-type instance-variableN;
return-type methodname1(parameter-list)
{
// Body of method
}
return-type methodname2(parameter-list)
{
// Body of method
}
}
Ex
public class IT{
int a;
public void dis(){
System.out.println("Number is "+a);
}
}
Object
- Instance of class that are created to use data members and methods of class.
- Object is created using new keyword.
Syntax:
class_name object_name = new class_name();
Ex:
It a1=new It();
Ex
a1.a;
a1.dis();
Method:
Method describe behavior of an object. A method is a collection of statements that
are group together to perform an operation.
Syntax of method is
return-type methodName(parameter-list)
{
//body of method}
Example of a Method
public String getName(String st){
String name="CoreJava";name=name+st;
return name;
}
Java tokens:
- Smallest individual unit in a program is called as token.
- Compiler identifies this tokens and work on them for conversion of source code
into byte code.
Types of Tokens
- Keyword
- Identifier
- Operator
- Literal
- Separator
- Comments
Keyword
- The reserved words whose meaning is predefined in java is called as keyword.
- In java there are 50 keywords.
- As keywords have different meaning we cannot use them as identifiers.
Identifiers
- They are used for naming classes, methods, variables, objects, packages and
interfaces.
- It is user-defined name.
- It uses alphabets, digits, underscore and dollar sign.
Literals
- Sequence of characters that represents constant values to be stored in a variable
is called as literal.
- Types of literals are Integer, Floating point, Character, String and Boolean
Operator
- Operator is a symbol that takes one or more argument and performs an operation on
them.
Separators:
- The symbols that are used for identifying the separation of group of code are
called separators.
- Ex parentheses(), Braces{}, Brackets[], Semicolon(;), Comma(,) , Period(.) .
Variable
- A variable is a storage location in computer memory.
- It has a specific data type which determines type of data it can hold.
- The value stored in variable can be changed during execution of program.
- There are three types of variables local, instance and static.
Ex
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
}
Constant
- Constant in java are variables whose values cannot be changed once assigned.
- In java constant are classified into numeric constant and string constants.
- final keyword is used to decalre constant.
Data types
- Data types specify type of data that variable can store in it.
- In java there are two types of data types primitive data types and non primitive
data types.
- Primitive data type
primitive data type represents basic type of data and they are predefined.
Here's a table summarizing the primitive data types in Java, including their size
in bits and the range of values they can represent:
Dynamic initialization
- Dynamic initialization in java refers to the process of initializing variables
with values that are calculated or determined at runtime.
- This allows for greater flexibility and adaptability in programming.
Ex
public class DE{
public static void main(String[] args){
int a=5,b=4;
int c=a+b;
System.out.println(c);
}
}
Type Casting
- The process of converting one data type to another is called as type casting.
- If two types are compatible then java will perform conversion automatically.
There are two types of conversion:
Implicit type casting:
Implicit type casting is performed by compiler automatically, if there will be no
loss of precision.
Ex:
int i=3;
double d=i;
output:
3.0
Explicit type casting:
To perform explicit typecasting, you need to specify the target data type in
parentheses before the value to be converted.
double d=3.5;
int i=(int)d;
output:
3
Operators
- Operator is a symbol that takes one or more argument and performs an operation on
them.
Expresssion
- Expression are combinations of operators and operands that produce a single
value.
Arithmetic Operator
Arithmetic operator are used to perform basic arithmetic operations.
Operator Meaning Syntax
+ Addition A + B
- Subtraction A - B
* Multiplication A * B
/ Division A / B
% Modulus A% B
++ Increment A++
-- Decrement A --
Relational Operator
Relational operator is used to compare two values.
Operator Meaning Syntax
== Equal to (A == B)
!= Not equal to (A != B)
> Greater than (A > B)
< Less than (A < B)
>= Greater than or equal to (A >= B)
<= Less than or equal to (A <= B)
Logical Operator
Logical operator is used to perform logical operation on boolean values
Operator Description Syntax
&& Logical AND operator. If both the operands are non-zero, (A &&
B)
then the condition becomes true.
Assignment operators
These operators are used for assigning result of an expression to variable.
Operator Meaning
= Normal assignment
+= x+=12; → x=x+12;
– = x– =7; → x=x–7;
*= x*=2; → x=x*2;
/= x/=2; → x=x/2;
Conditional Operator(Ternary)
Conditional operator is used to evaluate a boolean expression and return one of two
values based on result.
Syntax:
(Condition )? value1 : value2 ;
Bitwise operator
Bitwise operator is used to perform operations at bit level.
Operator Description Syntax
& Bitwise AND (A & B)
| Bitwise OR (A | B)
^ Bitwise exclusive OR (A ^ B)
~ Bitwise unary NOT (~A ).
<< Shift left A << 2
>> Shift right A >> 2
>>> Shift right zero fill A >>>2
Instance Of operator
Instance of operator is used to test whether an object is an instance of particular
class or interface.
Syntax:
object instanceof classname;
Returns true if object is instance of class or interface or any of it's subclasses.
Ex:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(sinstanceofSimple1);//true
}
}
Dot operator(.)
Dot operator is used to access members of class such as fields, methods.
Syntax:
object.member
object can be an instance of a class, an array, or a class name.
member can be a field (variable) or a method of the class.
Ex:
String str = "Hello";
int length = str.length(); // Accessing the length() method of the String class
System.out.println("Length of the string: " + length); // Output: Length of the
string: 5
Math Functions
Java supports basic math functions through Math class defined in java.lang package.
This should be used as Math.function_name.
Function Use
min(a,b) It computes the minimum of a & b
max(a,b) It computes the maximum of a & b
sqrt(double a) It computes square root of a
pow(double a, double b) It computes ab
exp(double a) It computes ea
round(x) Returns closest integer to x
abs(val) It computes the absolute value of val
log(val) It computes the logarithm values of val
ceil(val) It returns the smallest whole no. which is greater than or
equal to val
floor(val) It returns the largest whole no. which is lesser than or
equal to val
Ex
class d {
public static void main(String[] args) {
int a = 8, b = 5;
System.out.println(Math.max(a, b));
System.out.println(Math.min(a, b));
System.out.println(Math.sqrt(64));
System.out.println(Math.exp(4.0));
System.out.println(Math.log(45));
System.out.println(Math.abs(-56.4));
System.out.println(Math.round(53.45));
}
}
if statement:
If condition is true code inside if block is executed.
Syntax:
if(condition){
//statement to execute if condition is true.
}
if-else statement:
If a condition is true code inside if block is executed otherwise code in else
block is executed.
Syntax:
if(condition){
//statement to execute if condition is true.
}else{
//statement to execute if condition is false.
}
Loops:
a] for loop
A for loop in Java allows you to iterate over a block of code multiple times.
It consists of three parts: initialization, condition, and increment/decrement.
The initialization part is executed once at the beginning.
The condition is evaluated before each iteration. If it evaluates to true, the loop
continues; otherwise, the loop terminates.
The increment/decrement part is executed after each iteration.
Syntax:
for(initialization;condition;increment/decrement){
//code
}
b] While loop
A while loop repeatedly executes a target statement as long as a given condition is
true.
It evaluates the condition before the execution of the loop body. If the condition
is true, the loop body is executed. If it's false, the loop terminates.
Syntax:
initialization
while(condition){
//code
increment/decrement
}
c] Do While loop
A do-while loop is similar to a while loop, but the condition is evaluated after
the execution of the loop body.
This ensures that the loop body is executed at least once, even if the condition is
initially false.
Syntax:
initialization
do{
//code
increment/decrement
}while(condition);
d]For each
This is enhanced for loop. This loop helps in handling the array elements
efficiently without using a loop variable.
Syntax:
for (DataType element : arrayOrCollection) {
// body of the loop
}
break statement:
The break statement is used to terminate the loop immediately when a certain
condition is met.
It is commonly used to exit a loop prematurely based on some condition.
Once a break statement is encountered inside a loop, the loop is terminated, and
the program execution continues with the next statement after the loop.
continue statement:
The continue statement is used to skip the current iteration of the loop and
continue with the next iteration.
It is commonly used to skip certain iterations based on some condition, without
terminating the loop entirely.