0% found this document useful (0 votes)
24 views30 pages

Unit4 1

Java was initiated in 1991 as part of the Green Project at Sun Microsystems, originally named Oak, and officially released as Java 1.0 in 1995. The language has evolved through various versions, introducing significant features such as generics, lambda expressions, and a module system, with a focus on performance and security. Java operates on the principles of platform independence, object-oriented programming, and supports a wide range of data types and operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views30 pages

Unit4 1

Java was initiated in 1991 as part of the Green Project at Sun Microsystems, originally named Oak, and officially released as Java 1.0 in 1995. The language has evolved through various versions, introducing significant features such as generics, lambda expressions, and a module system, with a focus on performance and security. Java operates on the principles of platform independence, object-oriented programming, and supports a wide range of data types and operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

1.

Origin and Development

 1991:
o Java was initiated as part of the Green Project by James Gosling, Mike
Sheridan, and Patrick Naughton at Sun Microsystems.
o Initially designed for embedded systems in consumer electronics.
o The original language was called Oak, named after the oak tree outside
Gosling's office.
 1995:
o Oak was renamed Java after discovering that Oak was already a registered
trademark.
o Java 1.0 was officially released on May 23, 1995.
o The slogan: "Write Once, Run Anywhere" (WORA) highlighted its
platform independence.

2. Early Versions and Evolution

 Java 1.0 (1995):


o Basic version with core APIs and applet support.
 Java 1.1 (1997):
o Introduced JDBC (Java Database Connectivity), Inner Classes, and RMI
(Remote Method Invocation).

3. Major Versions Timeline

 Java 2 (J2SE 1.2) – 1998:


o Introduced Swing, Collections Framework, and Java Plug-in.
o Split into three editions:
 J2SE (Standard Edition)
 J2EE (Enterprise Edition)
 J2ME (Micro Edition)
 J2SE 1.3 (2000):
o Added HotSpot JVM and Java Naming and Directory Interface (JNDI).
 J2SE 1.4 (2002):
o Introduced regular expressions, assert keyword, and NIO (New I/O).

4. Modern Java Versions

 Java 5 (2004):
o Renamed to Java SE 5.
o Introduced generics, enhanced for-loop, and annotations.
 Java 6 (2006):
o Improved Web Services support and performance enhancements.
 Java 7 (2011):
o Introduced try-with-resources, switch with strings, and the diamond operator.
 Java 8 (2014):
o Introduced Lambda expressions, Stream API, and Date-Time API.
o Considered a revolutionary version with functional programming features.
 Java 9 (2017):
o Introduced the module system (Jigsaw).
o Added JShell for REPL (Read-Eval-Print Loop).
 Java 10 (2018):
o Introduced var for local variable type inference.
 Java 11 (2018):
o Long-Term Support (LTS) version.
o Removed JavaFX from core distribution.
 Java 12–16 (2019–2021):
o Added incremental improvements like switch expressions, records, and pattern
matching.
 Java 17 (2021):
o Another LTS version, introducing sealed classes and pattern matching
enhancements.
 Java 18–20 (2022–2023):
o Incremental improvements and performance enhancements.
 Java 21 (2023):
o Next LTS version, with updates to virtual threads, pattern matching, and more.

5. Acquisition by Oracle

 2010:
o Oracle Corporation acquired Sun Microsystems.
o Oracle continued the development of Java and introduced a new licensing
model.

6. Current Trends and Future

 Faster release cycles: Since Java 9, a new feature release occurs every 6 months.
 Focus on performance, security, and modularity.
 Growing adoption of GraalVM and native images for performance optimization.

Key Principles of Java

 Platform Independence (JVM)


 Object-Oriented Programming (OOP)
 Robust and Secure
 Multithreaded and Distributed

1. Features of Java

1.1 Platform Independent

 Java code is compiled into bytecode that runs on any platform using the JVM (Java
Virtual Machine).
 “Write Once, Run Anywhere (WORA)” principle.

1.2 Object-Oriented

 Follows OOP concepts such as:


o Class and Object
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

1.3 Simple and Easy to Learn

 Syntax is similar to C++ but eliminates complexities such as pointers and multiple
inheritance.

1.4 Secure

 Provides runtime security with features like bytecode verification and security APIs.
 Avoids explicit pointer manipulation.

1.5 Robust

 Strong memory management with automatic garbage collection.


 Exception handling prevents unexpected crashes.

1.6 Multithreaded

 Supports concurrent execution with multiple threads using APIs like Thread and
Runnable.

1.7 Distributed

 Facilitates distributed computing through APIs such as RMI (Remote Method


Invocation) and EJB (Enterprise JavaBeans).

1.8 High Performance

 Uses Just-In-Time (JIT) compiler to optimize code execution.

1.9 Dynamic and Extensible

 Supports dynamic class loading and integrates easily with other technologies.

1.10 Portable

 Bytecode can run on any platform that supports JVM.

What are Java Tokens?

 Java tokens are the smallest building blocks of a Java program.


 These tokens define the structure and syntax of a Java program
Example:
java
CopyEdit
public class HelloWorld {
public static void main(String[] args) {
int num = 10;
System.out.println("Hello, World!");
}
}

 Tokens in the above code:


o public, class, HelloWorld, {, }, main, String, args, int, num, 10,
System.out.println, ;

2. Types of Java Tokens

Java tokens are classified into 6 types:

2.1 Keywords

 Reserved words in Java that have a predefined meaning.


 Cannot be used as identifiers (class names, method names, or variable names).
 Total Keywords: 50+ in Java.

2.2 Identifiers

 Names assigned by the programmer to classes, methods, variables, and objects.


 Must follow Java naming conventions.

Rules:

 Must start with a letter, underscore _, or dollar sign $.


 Cannot use Java keywords.
 Case-sensitive

2.3 Literals

 Constant values assigned to variables.


 Types of Literals:
1. Integer Literals: 10, -25, 0xFF
2. Floating-Point Literals: 3.14, -0.001
3. Character Literals: 'A', '\n'
4. String Literals: "Hello", "Java"
5. Boolean Literals: true or false
6. Null Literal: null
Examples:
int num = 100; // Integer literal
float pi = 3.14f; // Floating-point literal
char grade = 'A'; // Character literal
String name = "Java"; // String literal
boolean isTrue = true; // Boolean literal
2.4 Operators

 Special symbols that perform operations on variables and values.


 Categories of Operators:
1. Arithmetic: +, -, *, /, %
2. Relational: ==, !=, >, <, >=, <=
3. Logical: &&, ||, !
4. Bitwise: &, |, ^, ~, <<, >>
5. Assignment: =, +=, -=, *=, /=
6. Increment/Decrement: ++, --
Examples:
int a = 5, b = 10;
int sum = a + b; // Addition operator
boolean isEqual = (a == b); // Relational operator

2.5 Separators

 Symbols that define boundaries and structure in the code.

Common Separators:
Symbol Purpose
{} Block of code
() Method parameter list
[] Array declaration
; End of a statement
, Separate multiple values
. Access class or object
Examples:
public class MyClass {
int[] arr = {1, 2, 3};
public void display() {
System.out.println("Hello");
}
}

2.6 Comments

 Comments are used to describe code and are ignored by the compiler.
Types of Comments:

1. Single-Line Comment: //
2. Multi-Line Comment: /* */
3. Documentation Comment: /** */

Examples:

int num = 10;

String name = "Java";

1. What is Java Character Set?

 A character set is a collection of valid characters that can be used in a Java program.
 Java uses the Unicode Standard to represent characters, which allows Java to support
multiple languages and platforms.

✅Unicode Basics:

 Unicode: A 16-bit character encoding system that supports over 65,000 characters.
 ASCII (American Standard Code for Information Interchange):
o Subset of Unicode.
o Represents characters using 7 bits (128 characters).

1. Java Keywords

 Keywords are reserved words in Java that have a predefined meaning and cannot be
used for naming variables, methods, classes, or other identifiers.

1.1 Characteristics of Keywords

 Keywords are case-sensitive (public is valid, but Public is not).


 They cannot be used as identifiers.
 Keywords are part of Java’s syntax and structure

Java Identifiers

 Identifiers are the names assigned by the programmer to variables, classes, methods,
and objects.
 They uniquely identify entities in a Java program.

Characteristics of Identifiers

 Can include letters, digits, underscore (_), and dollar sign ($).
 Must not start with a digit.
 Cannot be a Java keyword.
 Java identifiers are case-sensitive.

2.2 Rules for Identifiers

1. Start with a letter: Can start with A-Z, a-z, _, or $, but not with a digit.
2. Subsequent characters: Can be letters, digits, _, or $.
3. No spaces allowed: Identifiers cannot contain spaces.
4. Case-sensitive: age and Age are different identifiers.
5. Cannot be a keyword: class, int, or public cannot be used as an identifier.

1. What are Data Types in Java?

 Data types define the type of data that a variable can hold.
 Java is a statically typed language, meaning variables must be declared before use.
 Java data types are classified into:
o ✅Primitive Data Types (basic data types)
o ✅Non-Primitive Data Types (reference types)

Primitive Data Types in Java

Definition:

 Primitive data types are predefined by Java and directly store simple values.
 Java has 8 primitive data types, divided into four categories.

Non-Primitive Data Types in Java

Definition:

 Non-primitive data types (reference types) do not store values directly but hold
references to memory locations where data is stored.
 They can be user-defined and provide more complex data structures.

4.1 Types of Non-Primitive Data Types

1. String – Sequence of characters.


2. Arrays – Collection of elements of the same data type.
3. Classes – Blueprint for creating objects.
4. Interfaces – Blueprint that defines abstract methods.

Java Operators
Java operators are special symbols that perform operations on variables or values. They can be
classified into several categories based on their functionality. These operators play a crucial role in
performing arithmetic, logical, relational, and bitwise operations etc.

Example:
public class Geeks
{
public static void main(String[] args)
{

int num1 = 500;


int num2 = 100;
int sum = num1 + num2;
System.out.println("The Sum is: "+sum);

// Using the - (subtraction) operator


int diff = num1 - num2;
System.out.println("The Difference is: "+diff);

}
}

Types of Operators in Java


1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator

1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations
on primitive and non-primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
Example:
import java.io.*;
class Geeks
{
public static void main (String[] args)
{
int a = 10;
int b = 3;
String n1 = "15";
String n2 = "25";
int a1 = Integer.parseInt(n1);
int b1 = Integer.parseInt(n2);

System.out.println("a + b = " + (a + b));


System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("a1 + b1 = " + (a1 + b1));

}
}
2. Unary Operators
Unary Operators need only one operand. They are used to increment,
decrement, or negate a value.
 - , Negates the value.
 + , Indicates a positive value (automatically converts byte, char,
or short to int).
 ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
 -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
 ! , Inverts a boolean value.
Example:
import java.io.*;
class test {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;

// Using unary operators


System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));


System.out.println("Predecrement : " + (--b));
}
}
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It
has right-to-left associativity, i.e. value given on the right-hand side of
the operator is assigned to the variable on the left, and therefore right-
hand side value must be declared before using it or should be a
constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others
to create shorthand compound statements. For example, a +=
5 replaces a = a + 5. Common compound operators include:
 += , Add and assign.
 -= , Subtract and assign.
 *= , Multiply and assign.
 /= , Divide and assign.
 %= , Modulo and assign.
Example:
import java.io.*;
class test {
public static void main(String[] args)
{
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
4. Relational Operators
Relational Operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is ,
variable relation_operator value
Relational operators compare values and return boolean results:
 == , Equal to.
 != , Not equal to.
 < , Less than.
 <= , Less than or equal to.
 > , Greater than.
 >= , Greater than or equal to.
Example:
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int a = 10;
int b = 3;
int c = 5;
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR”
operations, similar to AND gate and OR gate in digital electronics. They
have a short-circuiting effect, meaning the second condition is not
evaluated if the first is false.
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-
versa
Example:
import java.io.*;
class Geeks {
public static void main (String[] args) {
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It
has three operands and hence the name Ternary. The general format is
,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then
execute the statements after the ‘?’ else execute the statements after
the ‘:’.
Example:
public class test {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "+ result);
}
}
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual
bits of a number and with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
 & (Bitwise AND) – returns bit-by-bit AND of input values.
 | (Bitwise OR) – returns bit-by-bit OR of input values.
 ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
 ~ (Bitwise Complement) – inverts all bits (one’s complement).

Example:
import java.io.*;
class Test
{
public static void main(String[] args)
{
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e : " + (d & e));
System.out.println("d | e : " + (d | e));
System.out.println("d ^ e : " + (d ^ e));
System.out.println("~d : " + (~d));
System.out.println("d << 2 : " + (d << 2));
System.out.println("e >> 1 : " + (e >> 1));
System.out.println("e >>> 1 : " + (e >>> 1));
}
}
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively. They
can be used when we have to multiply or divide a number by two. The
general format ,
number shift_op number_of_places_to_shift;
 << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of
two).
 >> (Signed right shift) – Shifts bits right, filling 0s (divides by a
power of two), with the leftmost bit depending on the sign.
 >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the
leftmost bit always 0.

Example:
import java.io.*;
class Geeks
{
public static void main(String[] args)
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}

instanceof operator
The instance of operator is used for type checking. It can be used to
test if an object is an instance of a class, a subclass, or an interface.
The general format ,
object instance of class/subclass/interface
Example:
public class Geeks
{
public static void main(String[] args)
{

Person obj1 = new Person();


Person obj2 = new Boy();
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Person {
}
class Boy extends Person implements MyInterface {
}
interface MyInterface {
}

What is Type Casting?


Type casting is a concept in programming where you change the data
type of a variable from one type to another. It's like changing a piece of
clay from one shape to another.
There are two types of type casting: implicit and explicit.
1. Implicit Type Casting (Coercion):
2. Explicit Type Casting (Casting):
Implicit Type Casting:
In implicit type casting, the programming language automatically
converts data from one type to another if needed. For example, if you
have an integer variable and you try to assign it to a float variable, the
programming language will automatically convert the integer to a float
without you having to do anything.
Advantages:
 Convenience: Implicit casting saves time and effort because you
don't have to manually convert data types.
 Automatic: It happens automatically, reducing the chance of errors
due to forgetting to convert types.
Disadvantages:
1. Loss of Precision: Sometimes, when converting between data
types, there can be a loss of precision. For example, converting from
a float to an integer may result in losing the decimal part of the
number.
2. Unexpected Results: Implicit casting can sometimes lead to
unexpected results if the programmer is not aware of how the
conversion rules work.
Explicit Type Casting:
Explicit type casting, also known as type conversion or type
coercion, occurs when the programmer explicitly converts a value from
one data type to another. Unlike implicit type casting, explicit type
casting requires the programmer to specify the desired data type
conversion.
Advantages:
 Control: Explicit type casting gives the programmer more control
over the conversion process, allowing for precise manipulation of
data types.
 Clarity: By explicitly indicating the type conversion, the code
becomes more readable and understandable to other developers.
 Avoidance of Loss of Precision: In cases where precision is
crucial, explicit type casting allows the programmer to handle the
conversion carefully to avoid loss of precision.
Disadvantages:
 Complexity: Explicit type casting can introduce complexity to the
code, especially when dealing with multiple data type conversions.
 Potential Errors: If the programmer incorrectly performs explicit
type casting, it may result in runtime errors or unexpected behavior.
 Additional Syntax: Explicit type casting requires additional syntax
or function calls, which may increase code verbosity.
Implicit Type Casting Syntax:
In implicit casting, the conversion happens automatically by the
programming language without the need for explicit instructions from
the programmer.

Example:
float num_float = 10.5;
int num_int = (int)num_float;

Implicit Type Casting Examples


Implicit type casting happens automatically by the programming
language. It converts a value from one type to another without any
explicit instruction from the programmer. Here are some examples:
Integer to Floating Point:

int_num = 5
float_num = int_num # Implicitly converts int to float

1. Java if Statement
The if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements will
be executed or not i.e. if a certain condition is true then a block of
statements is executed otherwise not.
Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if
statement accepts boolean values – if the value is true then it will
execute the block of statements under it. If we don’t use curly braces( {}
), only the next line after the if is considered as part of the if block For
example,
if (condition) // Assume condition is true
statement1; // Belongs to the if block
statement2; // Does NOT belong to the if block
Here’s what happens:
 If the condition is True statement1 executes.
 statement2 runs no matter what because it’s not a part of the if block
if Statement Execution Flow
The below diagram demonstrates the flow chart of an “if Statement
execution flow” in programming.

import java.util.*;

class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("Inside If block");
System.out.println("10 is less than 15");
System.out.println("I am Not in if");
}
}
2. Java if-else Statement
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false? Here, comes the
“else” statement. We can use the else statement with the if statement
to execute a block of code when the condition is false.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
if-else Statement Execution flow
The below diagram demonstrates the flow chart of an “if-else Statement
execution flow” in programmin

import java.util.*;
class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

Java nested-if Statement


A nested if is an if statement that is the target of another if or else.
Nested if statements mean an if statement inside an if statement. Yes,
java allows us to nest if statements within if statements. i.e, we can
place an if statement inside another if statement.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
nested-if Statement Execution Flow
The below diagram demonstrates the flow chart of an “nested-if
Statement execution flow” in programming

// Java program to demonstrate the


// working of nested-if statement
import java.util.*;

class Geeks {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i < 15) {
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println(
"i is smaller than 12 too");
}
else {
System.out.println("i is greater than 15");
}
}
}
4. Java if-else-if ladder
Here, a user can decide among multiple options.The if statements are
executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that ‘if’ is
executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed. There
can be as many as ‘else if’ blocks associated with one ‘if’ block but only
one ‘else’ block is allowed with one ‘if’ block.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
if-else-if ladder Execution Flow
The below diagram demonstrates the flow chart of an “if-else-if ladder
execution flow” in programming

import java.util.*;
class Geeks {
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Java Switch Case
The switch statement is a multiway branch statement. It provides an
easy way to dispatch execution to different parts of code based on the
value of the expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases…
default:
// code to be executed if no cases match
}
switch Statements Execution Flow
The below diagram demonstrates the flow chart of a “switch Statements
execution flow” in programming.

import java.io.*;
class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
System.out.println("It is 5");
break;
case 10:
System.out.println("It is 10");
break;
case 15:
System.out.println("It is 15");
break;
case 20:
System.out.println("It is 20");
break;
default:
System.out.println("Not present");
}
}
}
6. jump Statements
Java supports three jump statements: break, continue and return.
These three statements transfer control to another part of the program.
 Break: In Java, a break is majorly used for:

Terminate a sequence in a switch statement (discussed


o
above).
o To exit a loop.
o Used as a “civilized” form of goto.
 Continue: Sometimes it is useful to force an early iteration of a loop.
That is, you might want to continue running the loop but stop
processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to
the loop’s end. The continue statement performs such an action.
jump Statements Execution Flow
The below diagram demonstrates the flow chart of a “jump Statements
execution flow” in programming.
// Java program to demonstrates the use of
// continue in an if statement
import java.util.*;

class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {

// If the number is even


// skip and continue
if (i % 2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
}
}
Return Statement
The return statement is used to explicitly return from a method. That is,
it causes program control to transfer back to the caller of the method.
Example: The below Java program demonstrates how the return
statements stop a method and skips the rest of the code.

import java.util.*;
public class Geeks {
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");

if (t)
return;
System.out.println("This won't execute.");
}
}

C while and do...while Loop


In programming, loops are used to repeat a block of code until a specified condition is met.

C programming has three types of loops.

for loop
while loop
do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and
do..while loop.

while loop
The syntax of the while loop is:

while (testExpression) {
// the body of the loop
}

Java Class
A Class is a user-defined blueprint or prototype from which objects
are created. It represents the set of properties or methods that are
common to all objects of one type. Using classes, you can create
multiple objects with the same behavior instead of writing their code
multiple times. This includes classes for objects occurring more than
once in your code. In general, class declarations can include these
components in order:
 Modifiers: A class can be public or have default access (Refer
to this for details).
 Class name: The class name should begin with the initial letter
capitalized by convention.
 Body: The class body is surrounded by braces, { }.

Java Object
An Object is a basic unit of Object-Oriented Programming that
represents real-life entities. A typical Java program creates many
objects, which as you know, interact by invoking methods. The objects
are what perform your code, they are the part of your code visible to the
viewer/user. An object mainly consists of:
 State: It is represented by the attributes of an object. It also reflects
the properties of an object.
 Behavior: It is represented by the methods of an object. It also
reflects the response of an object to other objects.
 Identity: It is a unique name given to an object that enables it to
interact with other objects.
 Method: A method is a collection of statements that perform some
specific task and return the result to the caller. A method can
perform some specific task without returning anything. Methods
allow us to reuse the code without retyping it, which is why they are
considered time savers. In Java, every method must be part of
some class, which is different from languages like C, C++,
and Python.
Example:

public class Employee {


private String name;
private float salary;
public Employee(String name, float salary) {
this.name = name;
this.salary = salary;
}

public String getName() { return name; }


public float getSalary() { return salary; }
public void setName(String name) { this.name = name; }
public void setSalary(float salary) { this.salary = salary; }
public void displayDetails() {
System.out.println("Employee: " + name);
System.out.println("Salary: " + salary);
}

public static void main(String[] args) {


Employee emp = new Employee("Geek", 10000.0f);
emp.displayDetails();
}
}

Method and Method Passing


A method is a collection of statements that perform specific tasks and
return a result to the caller. It can be declared with or without
arguments, depending on the requirements. A method can take input
values, perform operations, and return a result.
Example:

// Class Method and Method Passing


class Student {
private int id;
private String name;

// Constructor for initialization


public Student(int id, String name) {
this.id = id;
this.name = name;
}

// method demonstrating parameter passing


public void printStudent(String header) {
System.out.println(header);
System.out.println("ID: " + getId());
System.out.println("Name: " + getName());
}

// Getter methods
public int getId() { return id; }
public String getName() { return name; }
}

class Main {
public static void main(String[] args) {
// Proper initialization
Student obj = new Student(28, "Geek");
// Method with parameter
obj.printStudent("Student Details:");
}
}
1. Abstraction
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user. Data Abstraction may also be defined as the
process of identifying only the required characteristics of an object,
ignoring the irrelevant details. The properties and behaviors of an
object differentiate it from other objects of similar type and also help in
classifying/grouping the object.
Real-life Example: Consider a real-life example of a man driving a car.
The man only knows that pressing the accelerators will increase the car
speed or applying brakes will stop the car, but he does not know how
on pressing the accelerator, the speed is actually increasing. He does
not know about the inner mechanism of the car or the implementation
of the accelerators, brakes etc. in the car. This is what abstraction is.
Note: In Java, abstraction is achieved by interfaces and abstract
classes. We can achieve 100% abstraction using interfaces.
Example:

abstract class Vehicle {


abstract void accelerate();
abstract void brake();
void startEngine() {
System.out.println("Engine started!");
}
}

class Car extends Vehicle {


void accelerate() {
System.out.println("Car: Pressing gas pedal...");
}

void brake() {
System.out.println("Car: Applying brakes...")
}
}

public class Main {


public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.startEngine();
myCar.accelerate();
myCar.brake();
}
}
2. Encapsulation
It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield
that prevents the data from being accessed by the code outside this
shield.
 Technically, in encapsulation, the variables or the data in a class is
hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
 In encapsulation, the data in a class is hidden from other classes,
which is similar to what data-hiding does. So, the terms
“encapsulation” and “data-hiding” are used interchangeably.
 Encapsulation can be achieved by declaring all the variables in a
class as private and writing public methods in the class to set and
get the values of the variables.
// Encapsulation using private modifier

class Employee {
// Private fields (encapsulated data)
private int id;
private String name;

// Setter methods
public void setId(int id) {
this.id = id;
}

public void setName(String name) {


this.name = name;
}

// Getter methods
public int getId() {
return id;
}

public String getName() {


return name;
}
}

public class Main {


public static void main(String[] args) {
Employee emp = new Employee();

emp.setId(101);
emp.setName("Geek");
System.out.println("Employee ID: " + emp.getId());
System.out.println("Employee Name: " + emp.getName());
}
}
Inheritance
Inheritance is an important pillar of OOP (Object Oriented
Programming). It is the mechanism in Java by which one class is
allowed to inherit the features (fields and methods) of another class.
We are achieving inheritance by using extends keyword. Inheritance is
also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
 Superclass: The class whose features are inherited is known as
superclass (also known as base or parent class).
 Subclass: The class that inherits the other class is known as
subclass (also known as derived or extended or child class). The
subclass can add its own fields and methods in addition to the
superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new
class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
// Superclass (Parent)
class Animal {
void eat() {
System.out.println("Animal is eating...");
}

void sleep() {
System.out.println("Animal is sleeping...");
}
}

// Subclass (Child) - Inherits from Animal


class Dog extends Animal {
void bark() {
System.out.println("Dog is barking!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();

// Inherited methods (from Animal)


myDog.eat();
myDog.sleep();

// Child class method


myDog.bark();
}
}
Polymorphism
It refers to the ability of object-oriented programming languages to
differentiate between entities with the same name efficiently. This
is done by Java with the help of the signature and declaration of these
entities. The ability to appear in many forms is called polymorphism.
Example:
sleep(1000) //millis
sleep(1000,2000) //millis,nanos
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:
1. Method Overloading
2. Method Overriding
Method Overloading and Method Overriding
1. Method Overloading: Also, known as compile-time
polymorphism, is the concept of Polymorphism where more than one
method share the same name with different signature(Parameters) in a
class. The return type of these methods can or cannot be same.
2. Method Overriding: Also, known as run-time polymorphism, is the
concept of Polymorphism where method in the child class has the same
name, return-type and parameters as in parent class. The child class
provides the implementation in the method already written.
// Java Program to Demonstrate
// Method Overloading and Overriding

// Parent Class
class Parent {
// Overloaded method (compile-time polymorphism)
public void func() {
System.out.println("Parent.func()");
}

// Overloaded method (same name, different parameter)


public void func(int a) {
System.out.println("Parent.func(int): " + a);
}
}

// Child Class
class Child extends Parent {
// Overrides Parent.func(int) (runtime polymorphism)
@Override
public void func(int a) {
System.out.println("Child.func(int): " + a);
}
}

public class Main {


public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
// Dynamic dispatch
Parent polymorphicObj = new Child();

// Method Overloading (compile-time)


parent.func();
parent.func(10);

// Method Overriding (runtime)


child.func(20);

// Polymorphism in action
polymorphicObj.func(30);
}
}
Advantage of OOPs over Procedure-Oriented Programming
Language
Object-oriented programming (OOP) offers several key advantages
over procedural programming:
 OOP promotes code reusability: By using objects and classes,
you can create reusable components, leading to less duplication and
more efficient development.
 OOP enhances code organization: It provides a clear and logical
structure, making the code easier to understand, maintain, and
debug.
 OOP supports the DRY (Don’t Repeat Yourself) principle: This
principle encourages minimizing code repetition, leading to cleaner,
more maintainable code. Common functionalities are placed in a
single location and reused, reducing redundancy.
 OOP enables faster development: By reusing existing code and
creating modular components, OOP allows for quicker and more
efficient application development

What is HTML?
 HTML stands for Hyper Text Markup Language
 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a heading", "this
is a paragraph", "this is a link", etc.

HTML Document
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

HTML Links - Hyperlinks


HTML links are hyperlinks.

You can click on a link and jump to another document.

When you move the mouse over a link, the mouse arrow will turn into a little
hand.
HTML Links - Syntax
The HTML <a> tag defines a hyperlink. It has the following syntax:

<a href="url">link text</a>

The most important attribute of the <a> element is the href attribute, which
indicates the link's destination.

The link text is the part that will be visible to the reader.

Clicking on the link text, will send the reader to the specified URL address.

Example
<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>
Try it Yourself »

You might also like