[go: up one dir, main page]

0% found this document useful (0 votes)
20 views20 pages

unit-1 java

Uploaded by

abhikannadiga20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views20 pages

unit-1 java

Uploaded by

abhikannadiga20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

INTRODUCTION TO JAVA

History of java
Java’s history is as interesting as it is impactful. The journey of this
powerful programming language began in 1991 when James Gosling, Mike Sheridan,
and Patrick Naughton, a team of engineers at Sun Microsystems known as the “Green
Team,” set out to create a new language initially called “Oak.” Oak was later
renamed Java, inspired by Java coffee, and was first publicly released in 1995 as Java 1.0.
This initial version provided a no-cost runtime environment across popular platforms,
making it accessible to a broad audience. Arthur Van Hoff rewrote the Java 1.0
compiler to strictly comply with its specifications, ensuring its reliability and cross-
platform capabilities.

 Java evolved over time, with Java 2 introducing multiple configurations tailored for
different platforms, showcasing its versatility.
 In 1997, Sun Microsystems aimed to formalize Java through the ISO standards
body but eventually withdrew from the process.
 Despite not formalizing through ISO, Sun Microsystems offered most Java
implementations at no cost, earning revenue by licensing specialized products such as
the Java Enterprise System.
 A significant milestone in Java’s history occurred on November 13, 2006, when Sun
Microsystems released a large portion of the Java Virtual Machine (JVM) as free,
open-source software.
 By May 8, 2007, the core JVM code was fully available under open-source distribution
terms.
 Java was designed with core principles: simplicity, robustness, security, high
performance, portability, multi-threading, and dynamic interpretation. These
principles have made Java a preferred language for various applications, including
mobile devices, internet programming, gaming, and e-business.
 Today, Java continues to be a cornerstone of modern software development, widely
used across industries and platforms.

Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode
generated by the compiler. This byte code can run on any platform be it Windows, Linux,
or macOS which means if we compile a program on Windows, then we can run it
on Linux and vice versa. Each operating system has a different JVM, but the output
produced by all the OS is the same after the execution of the byte code. That is why we call
java a platform-independent language.

2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing
the program in the terms of a collection of objects is a way of object-oriented programming,
each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It
eliminates complex features like pointers and multiple inheritances, making it easier
to write, debug, and maintain code.

4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a lot
of effort into checking errors as early as possible, that is why the java compiler is able to
detect even those errors that are not easy to detect by another programming language. The
main features of java that make it robust are garbage collection, exception handling, and
memory allocation.

5. Security
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also, java
programs run in an environment that is independent of the os(operating
system) environment which makes java programs more secure.

6. Distributed
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications
in java. The java programs can be easily distributed on one or more systems that are
connected to each other through an internet connection.

7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a
program. This feature is particularly useful for applications that require high performance,
such as games and real-time simulations.

8. Portability
As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform-independent bytecode can be
taken to any platform for execution makes java portable. WORA(Write Once Run
Anywhere) makes java application to generates a ‘.class’ file that corresponds to our
applications(program) but contains code in binary format. It provides architecture-neutral
ease, as bytecode is independent of any machine architecture. It is the primary reason java
is used in the enterprising IT industry globally worldwide.

9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and at
some times java uses Just In Time (JIT) compiler where the compiler compiles code on-
demand basis where it only compiles those methods that are called making applications to
execute faster.
JDK Environment and tools

The Java Development Kit (JDK) is a cross-platformed software development


environment that offers a collection of tools and libraries necessary for developing Java-
based software applications and applets. It is a core package used in Java, along with
the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment).

Beginners often get confused with JRE and JDK, if you are only interested in
running Java programs on your machine then you can easily do it using Java Runtime
Environment. However, if you would like to develop a Java-based software application
then along with JRE you may need some additional necessary tools, which is called JDK.

JDK=JRE+Development Tools

Java: The Java Application launcher Executes Java application and applets. it replaces the
older jre tool, combining development and deployment functionalities.

Javac: Java compiler converts Java Source code into Java bytecode, producing. Class files.

applet viewer: Runs and debugs Java applets, without a web browser

Java doc: Documentation gnenerator Automatically create HTML documentation from


Java source code comments

Jdb: Java debugger provides a command-line interface for debugging Java programs.
JVM: The JVM is a park of the Java platform that executes Java byte code, converting it into
machine code for the host system. it provides an abstraction layer between compiled Java
code and the operating system.

OOPS CONCEPTS OF JAVA

ENCAPSULATION :
Encapsulation is a process of giving controled access to very important aspect of an
object for Performing encapsulation.
1) we identify the important aspect.
2) we have to restric to direct access by declaring the important aspect as private.
(3) we have to give controled access to the Private Member by using Public Seters & geters
Hence we can conclude that encapsulation is process of binding data members with member
functions.

Example:
Class TextBook
{
private int Page-no:
public void setpageno (int x)
{
If(x>0)
{
Page-no=x;
}
else
{
System.out.println(“Invalid Page_no "),
}
}
public int getpage_no();
{
Return Page-no;
}
}

Class Encapsulation
{
public static void main (String []args)
{
TextBook tb=new TextBook();
tb.setpageno (100),
System.out.println(“page no of textbook is " + tb.getpageno());
}
}

INHERITANCE
Inheritance in Java enables a class to inherit properties and actions from another class,
called a superclass or parent class. A class derived from a superclass is called a subclass or
child group. Through inheritance, a subclass can access members of its superclass (fields and
methods), enforce reuse rules, and encourage hierarchy.
Syntax
class Subclass-name extends Superclass-name
{
//methods and fields
}

Example:
class Employee
{
float salary=40000;
}

class Programmer extends Employee


{
int bonus=10000;
}

public class Main


{
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many forms.

Examples:

class Bike
{
void run(){System.out.println("running");}
}

class Splendor extends Bike


{
void run(){System.out.println("running safely with 60km");}
}

public class Main


{
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}

ABSTRACT CLASS
In the world of Java programming, abstract classes play an important role in defining
the structure of classes and their behavior in the hierarchy. They provide a blueprint for other
teams to follow, and some methods remain undefined. This flexibility empowers developers
to generate a well-organized and scalable codebase. In this section, we will explore the
concept of abstract classes in Java, examining their features, advantages, and best practices.

A class that is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Example:

abstract class Bike


{
abstract void run();
}

//Creating a child class and override abstract method


class Honda extends Bike
{
void run()
{
System.out.println("running safely");
}
}

//Creating a Main class to create object and call methods


public class Main
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
}
}
DIFFERENCE BETWEEN JAVA AND C++

Parameters Java C++

C++ was Influenced by


Java was Influenced by Ada Influenced by Ada,
83, Pascal, C++, C#, etc. ALGOL 68, C, ML,
languages. Simula, Smalltalk, etc.
Influenced By languages.

C++ was influenced to


Java was influenced to develop
develop C99, Java, JS++,
BeanShell, C#, Clojure,
Lua, Perl, PHP, Python,
Groovy, Hack, J#, Kotlin, PHP,
Rust, Seed7, etc.
Python, Scala, etc. languages.
Influenced to languages.

Platform-independent, Java Platform dependent


Platform bytecode works on any should be compiled for
Dependency operating system. different platforms.

C++ is platform-
It can run on any OS hence it
dependent. Hence it is
is portable.
Portability not portable.

Java is both a Compiled and C++ is a Compiled


Compilation Interpreted Language. Language.

Memory Memory Management is Memory Management in


Management System Controlled. C++ is Manual.

It supports only single


inheritance. Multiple It supports both single
Multiple inheritances are achieved and multiple Inheritance.
Inheritance partially using interfaces.

It supports only method


It supports both method
overloading and doesn't allow
and operator overloading.
Overloading operator overloading.

It has limited support for It strongly supports


Pointers pointers. pointers.
Parameters Java C++

Java doesn't support the goto C++ supports the goto


goto Keyword Keyword keyword.

Structures Java doesn't support C++ supports Structures


and Unions Structures and Unions. and Unions.

Java is not so interactive with C++ is nearer to


Hardware hardware. hardware

STRUCTURE OF JAVA PROGRAM

A Java program involves the following sections:

 Documentation Section
 Package Statement
 Import Statements
 Interface Statement
 Class Definition
 Main Method Class
 Main Method Definition
Section Description
Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are
optional, but we suggest you use them because they are useful to
understand the operation of the program, so you must write comments within
the program.

Ex : // First java program


/* Write java program addition of
Two numbers */

Package You can create a package with any name. A package is a group of classes
statement that are defined by a name. That is, if you want to declare many classes
within one element, then you can declare it within a package. It is an optional
part of the program, i.e., if you do not want to declare any package, then
there will be no problem with it, and you will not get any errors. Here, the
package is a keyword that tells the compiler that package has been created.
It is declared as:

Ex : package package_name;
Import This line indicates that if you want to use a class of another package, then
statements you can do this by importing it directly into your program.
Example:

Ex : import calc.add;

Interface Interfaces are like a class that includes a group of method declarations. It's
statement an optional section and can be used when programmers want to implement
multiple inheritances within a program.

Class Definition A Java program may contain several class definitions. Classes are the main
and essential elements of any Java program.

Ex : Class classname

Main Method Every Java stand-alone program requires the main method as the starting
Class point of the program. This is an essential part of a Java program. There may
be many classes in a Java program, and only one class defines the main
method. Methods contain data type declaration and executable statements.

Ex : public static void main(String


[]args)
{
//Statements
}

Example:
//Name of this file will be "Hello.java"
public class Hello

public static void main(String[] args)

System.out.println("Hello Java");

DATA TYPES IN JAVA


In programming languages, data types specify the different sizes and values that can be
stored in the variable or constants. Each data type is predefined, which makes Java a
statically and strongly typed language. There are the following two types of data types in
Java.

1. Primitive Data Types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-Primitive Data Types: The non-primitive data types include Classes, Interfaces,
String, and Arrays.
Java Primitive Data Types
In Java, primitive data types are the building blocks of data manipulation. These are the basic
data types.

In Java, there are mainly eight primitive data types which are as follows.

1. boolean data type


2. char data type
3. byte data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type

1. Boolean Data Type

In Java, the boolean data type represents a single bit of information with two possible
states: true or false. The size of the Boolean data type is 1 byte (8 bits).

Syntax:

boolean flag;

Example:
Boolean a = false;
Boolean b = true;

2. Byte Data Type

The byte data type in Java is a primitive data type that represents an 8-bits signed two's
complement integer. It has a range of values from -128 to 127. Its default value is 0.

Syntax:

byte size;

Example:
byte a = 10;
byte b = -20;

3. Short Data Type


The short data type in Java is a primitive data type that represents a 16-bits signed two-
complement integer. Its range of values is -32,768 to 32,767.

Syntax:

short var;

Example:
short a = 10000;
short b = -5000;

4. int Data Type

The int data type in Java is a primitive data type that represents a 32-bits signed two's
complement integer. It has a range of values from -2,147,483,648 to 2,147,483,647.

Syntax:

int myInt = 54;

Example
int a = 100000;
int b = -200000;

5. long Data Type

The long data type in Java is a primitive data type that represents a 64-bits signed two's
complement integer. It has a wider range of values than int, ranging from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Its default value is 0.0L or 0.0l.

Syntax:

long num = 15000000000L;


long num = 9,223,372,036,854,775l

Example:
long a = 5000000L;
long b = -6000000L;

6. float Data Type

The float data type in Java is a primitive data type that represents single-precision 32-
bits IEEE 754 floating-point numbers. It can represent a wide range of decimal values, but it
is not suitable for precise values such as currency. Its default value is 0.0f or 0.0F.
The float data type is useful for applications where a higher range of values is needed and
precision is not critical.

Syntax:

float num = 67;

Example:
float f = 234.5f;

7. double Data Type

The double data type in Java is a primitive data type that represents double-precision 64-bits
IEEE 754 floating-point numbers. Its default value is 0.0. It provides a wider range of values
and greater precision compared to the float data type, which makes it suitable for applications
where accurate representation of decimal values is required.

Syntax:

double num = 75.658d;

Example:
double d = 12.3;

8. char Data Type

The char data type in Java is a primitive data type that represents a single 16-bits Unicode
character. It can store any character from the Unicode character set, which allows Java to
support the internationalisation and representation of characters from various languages and
writing systems.

Syntax:

char alphabets = 'J';


char a = 60, b = 61, c = 62;

Example:
char c = 'A';

Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods
in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

Example of Local Variable

//defining a Local Variable


int num = 10;
System.out.println(" Variable: " + num);

Output:
Variable: 10

2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and


is not shared among instances.

Example of Instance Variable

public class InstanceVariableDemo {


//Defining Instance Variables
public String name;
public int age=19;
//Creadting a default Constructor initializing Instance Variable
public InstanceVariableDemo()
{
this.name = "Deepak";
}
}

public class Main


{
public static void main(String[] args)
{
// Object Creation
InstanceVariableDemo obj = new InstanceVariableDemo();
System.out.println("Student Name is: " + obj.name);
System.out.println("Age: "+ obj.age);
}
}
Output:
Student Name is: Deepak
Age: 19

3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.

Example Static variable

class Student
{
//static variable
static int age;
}

public class Main


{
public static void main(String args[]){
Student s1 = new Student();
Student s2 = new Student();
s1.age = 24;
s2.age = 21;
Student.age = 23;
System.out.println("S1\'s age is: " + s1.age);
System.out.println("S2\'s age is: " + s2.age);
}
}

Java Operators
Java operators are special symbols that perform operations on variables or
values. These operators are essential in programming as they allow you to manipulate
data efficiently. They can be classified into different categories based on their
functionality. In this article, we will explore different types of operators in Java,
including arithmetic, unary, relational, logical, and more, along with practical examples.

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

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.

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.

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.

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

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 ‘:’.

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).

Java Keywords


In Java, keywords are the reserved words that have some predefined
meanings and are used by the Java compiler for some internal process or represent
some predefined actions. These words cannot be used as identifiers such
as variable names, method names, class names, or object names.

Keywords Usage

Specifies that a class or method will


abstract
be implemented later, in a subclass
Keywords Usage

Assert describes a predicate placed


in a Java program to indicate that the
assert
developer thinks that the predicate is
always true at that place.

A data type that can hold True and


boolean
False values only

A control statement for breaking out


break
of loops.

A data type that can hold 8-bit data


byte
values

Used in switch statements to mark


case
blocks of text

Catches exceptions generated by try


catch
statements

A data type that can hold unsigned


char
16-bit Unicode characters

class Declares a new class

const Reserved but not used

continue Sends control back outside a loop

Specifies the default block of code in


default
a switch statement

do Starts a do-while loop

Naming Conventions in Java


In java, it is good practice to name class, variables, and methods name as what they
are actually supposed to do instead of naming them randomly. Below are some naming
conventions of the java programming language. They must be followed while developing
software in java for good maintenance and readability of code. Java uses CamelCase as a
practice for writing names of methods, variables, classes, packages, and constants.

Camel’s case in java programming consists of compound words or phrases such that each
word or abbreviation begins with a capital letter or first word with a lowercase letter, rest
all with capital. Here in simpler terms, it means if there are two

Type 1: Classes and Interfaces


 Class names should be nouns, in mixed cases with the first letter of each internal word
capitalized. Interfaces names should also be capitalized just like class names.
 Use whole words and must avoid acronyms and abbreviations.
Classes: class Student { }
class Integer {}
class Scanner {}
Interfaces : Runnable
Remote
Serializable

Type 2: Methods
 Methods should be verbs, in mixed case with the first letter lowercase and with the
first letter of each internal word capitalized.
public static void main(String [] args) {}
As the name suggests the method is supposed to be primarily method which indeed it is as
main() method in java is the method from where the program begins its execution.

Type 3: Variables
Variable names should be short yet meaningful.
Variable names should not start with underscore _ or dollar sign $ characters, even though
both are allowed.
 Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
 One-character variable names should be avoided except for temporary variables.
 Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for
characters.
int[] marks;
double double answer,

Type 4: Constant variables


 Should be all uppercase with words separated by underscores (“_”).
 There are various constants used in predefined classes like Float, Long, String etc.
num = PI;

Type 5: Packages
 The prefix of a unique package name is always written in all-lowercase ASCII
letters and should be one of the top-level domain names, like com, edu, gov, mil, net,
org.
 Subsequent components of the package name vary according to an organization’s own
internal naming conventions.
java.util.Scanner;
java.io.*;

You might also like