JAVA Unit 1
JAVA Unit 1
Features of Java
• Java is simple-java is very easy to learn, and its syntax is simple, clean and easy to
understand
• Java is object-oriented-Java is an object-oriented programming language. Everything in
Java is an object.
• Java is distributed-Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed applications.
• Java is interpreted-It is executed in line-by-line statements in java programming
• Java is robust-it uses strong memory management. and There is a lack of pointers that
avoids security problems.
• Java is secure-No explicit pointer and Java Programs run inside a virtual machine
sandbox
• Java is architecture-neutral-n 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.
• Java is portable -Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.
• Platform independent-Java code can be run 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).
• Java’s performance-
• Java is multithreaded-A thread is like a separate program, executing concurrently. We
can write Java programs that deal with many tasks at once by defining multiple threads.
• Java is dynamic -Java is a dynamic language. It supports dynamic loading of classes. It
means classes are loaded on demand.
High Performance-Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code.
Object oriented Concepts
• Oriented Programming is a paradigm that provides many concepts, such as inheritance,
data binding, polymorphism, etc.
• Simula is considered the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as a truly object-oriented
programming language.
• Smalltalk is considered the first truly object-oriented programming language.
• The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
• The main aim of object-oriented programming is to implement real-world entities, for
example, object, classes, abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)
• Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
• Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
• Coupling
• Cohesion
• Association
• Aggregation and Composition
Object
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
• An Object can be defined as an instance of a class.
• An object contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or code.
• The only necessary thing is the type of message accepted and the type of response
returned by the objects.
• Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual
object.
• Class doesn't consume any space Inheritance
•
When one object acquires all the properties and behaviors of a parent object, it is known
as inheritance.
• It provides code reusability.
• It is used to achieve runtime polymorphism. Polymorphism
• If one task is performed in different ways, it is known as polymorphism.
• For example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve polymorphism.
• Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
• Hiding internal details and showing functionality is known as abstraction.
• For example phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation.
Java bean is the fully encapsulated class because all the data members are private here
Coupling
• Coupling refers to the knowledge or information or dependency of another class.
• It arises when classes are aware of each other. If a class has the details information of
another class, there is strong coupling.
• In Java, we use private, protected, and public modifiers to display the visibility level of a
class, method, and field.
Cohesion
• Cohesion refers to the level of a component which performs a single well-defined task.
• A single well-defined task is done by a highly cohesive method.
• The weakly cohesive method will split the task into separate parts.
• The java.io package is a highly cohesive package because it has I/O related classes and
interface.
• However, the java.util package is a weakly cohesive package because it has unrelated
classes and interfaces.
Association
• Association represents the relationship between the objects.
• Here, one object can be associated with one object or many objects.
• There can be four types of association between the objects:
• One to One
• One to Many
• Many to One, and • Many to Many
• Let's understand the relationship with real-time examples.
•
For example, One country can have one prime minister (one to one), and a prime minister
can have many ministers (one to many). Also, many MP's can have one prime minister
(many to one), and many ministers can have many departments (many to many).
• Association can be undirectional or bidirectional.
Aggregation
• Aggregation is a way to achieve Association.
• Aggregation represents the relationship where one object contains other objects as a part
of its state.
• It represents the weak relationship between objects.
• It is also termed as a has-a relationship in Java. Like, inheritance represents the isa
relationship. It is another way to reuse objects.
Composition
• The composition is also a way to achieve Association.
• The composition represents the relationship where one object contains other objects as a
part of its state.
• There is a strong relationship between the containing object and the dependent object.
• It is the state where containing objects do not have an independent existence.
• If you delete the parent object, all the child objects will be deleted automatically. Lexical
Issues
The Java compiler recognizes five kinds of tokens: identifiers, keywords, literals, operators,
and miscellaneous separators. Comments and white space such as blanks, tabs, line feeds,
and are not tokens, but they often are used to separate tokens
Java keywords
• Java keywords are also known as reserved words.
• Keywords are particular words which acts as a key to a code. These are predefined words
by Java so it cannot be used as a variable or object name.
• A keyword is a reserved word in Java language. Keywords are used to perform a specific
task in the computer program. For example, to define variables, do repetitive tasks or
perform logical operations.
• Java is rich in keywords.such as abstract continue for new switch assert default goto
package synchronized boolean do if private this break double implements protected
throw byte else import public throws case enum instanceof return transient catch
extends int short try char final interface static var class finally long strictfp void
const float native super volatile while Java identifiers
• Identifiers are names for variables, methods, classes, or parameters. Identifiers can have
alphanumerical characters, underscores and dollar signs ($). It is an error to begin a
variable name with a number. White space in names is not permitted.
• Identifiers are case sensitive. This means that Name, name, or NAME refer to three
different variables. Identifiers also cannot match language keywords.
• String name23; int _col; short car_age; These are valid Java identifiers. Java literals
•
• A literal is a textual representation of a particular value of a type. Literal types include
boolean, integer, floating point, string, null, or character. Technically, a literal will be
assigned a value at compile time, while a variable will be assigned at runtime.
int age = 29; String nationality = "Hungarian";
Java operators
• An operator is a symbol used to perform an action on some value. Operators are used in
expressions to describe operations involving one or more operands.
• + - * / % ^ & | ! ~ = += -= *= /= %= ^= ++ -- == != < > &= >>= <<= >= <= || && >> <<
?: This is a partial list of Java operators.
Java separators.
• A separator is a sequence of one or more characters used to specify the boundary
between separate, independent regions in plain text or other data stream.
• [ ] ( ) { } , ; . " String language = "Java"; The double quotes are used to mark the
beginning and the end of a string. The semicolon ; character is used to end each Java
statement.
Data types and variables
Data Types in Java
• Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
• Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
• Java Primitive Data Types
• In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
There are 8 types of primitive data types:
• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
• 10 20 70 40 50
Declaration, Instantiation and Initialization of Java Array
• We can declare, instantiate and initialize the java array together by:
• int a[]={33,3,4,5};//declaration, instantiation and initialization
//Java Program to illustrate the use of declaration, instantiation and initialization of Jav
a array in a single line • class Testarray1{
• public static void main(String args[]){
• int a[]={33,3,4,5};//declaration, instantiation and initialization
• //printing array
• for(int i=0;i<a.length;i++)//length is the property of array
• System.out.println(a[i]);
• }} • Output:
• 33 3 4 5
Java operators
• Operators are used to perform operations on variables and values.
• In the example below, we use the + operator to add together two values:
• Example
• int x = 100 + 50;
• Although the + operator is often used to add together two values, like in the example
above, it can also be used to add together a variable and a value, or a variable and another
variable:
Types of operators
• Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
• Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic operators
Arithmetic operators are used to perform common mathematical operations
• Example
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
• int x = 10;
== Equal to x == y
!= Not equal x != y
•
Java logical operators
Logical operators are used to determine the logic between variables or values
! Logical not Reverse the result, returns !(x < 5 && x <
false if the result is true 10)
Java Bitwise operators
Bitwise operators are used to perform binary logic with the bits of an integer or long integer
& AND - Sets each bit to 1 if both bits are 1 1 0101 & 0001 1
5&
0001
| 1 0101 5
OR - Sets each bit to 1 if any of the two bits 5 | 0101 |
is 1 0001
~
NOT - Inverts all the bits ~5 ~0101 1010 10
>> Signed right shift - Shift right by pushing 9 >> 1 1001 >> 1 1100 12
copies of the leftmost bit in from the left
and letting the rightmost bits fall off
>>> Zero-fill right shift - Shift right by pushing 9 >>> 1 1001 >>> 1 0100 4
zeroes in from the left and letting the
rightmost bits fall off
Control statements:
• Selection
• Iteration and • jump Statement.
Selection
Java Conditions and If Statements
•
•
•
•
Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
Conditional statements
• Java has the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true(if
statement)
• Use else to specify a block of code to be executed, if the same condition is false(if–else
statement)
• Use else if to specify a new condition to test, if the first condition is false(if–elseif
statement)
• Use switch to specify many alternative blocks of code to be executed(switch statement)
If statement
• Use the if statement to specify a block of Java code to be executed if a condition is true.
• Syntax
• if (condition)
• { // block of code to be executed if the condition is true }
• Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
• Example
• int x = 20;
• int y = 18;
• if (x > y)
• { System.out.println("x is greater than y");
• }
The else statement
• Use the else statement to specify a block of code to be executed if the condition is false.
• 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 }
• Example
• int time = 20;
• if (time < 18)
•
•
•
•
•
• { System.out.println("Good day."); }
• else
• { System.out.println("Good evening."); }
• // Outputs "Good evening."
The elseif statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1)
{ // block of code to be executed if condition1 is true }
else if (condition2)
• { // block of code to be executed if the condition1 is false and condition2 is true } •
else
• { // block of code to be executed if the condition1 is false and condition2 is false }
Example
• int time = 22;
• if (time < 10)
• { System.out.println("Good morning."); }
• else if (time < 20)
• { System.out.println("Good day."); }
• else
• { System.out.println("Good evening."); }
• // Outputs "Good evening."
Short Hand If...Else (Ternary Operator)
• There is also a short-hand if else, which is known as the ternary operator because it
consists of three operands.
• It can be used to replace multiple lines of code with a single line.
• It is often used to replace simple if else statements:
Syntax
• variable = (condition) ? expressionTrue : expressionFalse;
• //program
• int time = 20;
• if (time < 18)
• { System.out.println("Good day."); }
• Else
• { System.out.println("Good evening."); }
•
•
•
•
•
•
• You can simply write:
• Example
• int time = 20;
• String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result);
Java break
It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when i is equal to 4:
•
•
•
•
•
•
•
•
•
• the break statement
• goto statement and •
the return statement.
Goto statements java does not support goto, it is reserved as a keyword just in case they
wanted to add it to a later version.
Unlike C/C++, Java does not have goto statement, but java supports label.
The only place where a label is useful in Java is right before nested loop statements