22cds42-Module-1-Notes-updated
22cds42-Module-1-Notes-updated
Introduction to Java: The Java Language, Java Development Kit (JDK); Java Buzzwords,
Byte Code, JVM ,JRE and Java environment, Data types, variables and Arrays, Operators,
Control statement, command line Arguments, Language fundamentals Object Oriented
Programming with JAVA: Object Oriented concepts, Classes, Objects and Methods, Method
Overloading, Constructor, static members, Implicit this.
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first
working version. This language was initially called “Oak,” but was renamed “Java” in
1995.
Java is a general-purpose programming language that is class-based, object-
oriented, and designed to have as few implementation dependencies as possible.
It is intended to let application developers write once, run
anywhere (WORA) meaning that compiled Java code can run on all platforms that
support Java without the need for recompilation.
Java applications are typically compiled to bytecode that can run on any Java virtual
machine (JVM) regardless of the underlying computer architecture.
The primary motivation was the need for a platform-independent (that is, architecture-
neutral) language that could be used to create software to be embedded in various
consumer electronic devices, such as microwave ovens and remote controls.
Used to create Desktop applications, Web applications, Mobile applications and
Enterprise applications.
The Java Development Kit (JDK) is an implementation of either one of the , Java Platform,
Enterprise Edition, or Java Platform, Micro Edition platforms released by Oracle
Corporation in the form of a binary product aimed at Java developers
on Solaris, Linux, macOS or Windows. The JDK includes a private JVM and a few other
resources to finish the development of a Java Application. Since the introduction of
the Java platform, it has been by far the most widely used Software Development Kit (SDK).
The JDK has as its primary components a collection of programming tools, including:
javac – the Java compiler, which converts source code into Java bytecode.
Javadoc – documentation generator, which automatically generates documentation
from source code.
Jar- the archiver , which packages related class libraries into a single JAR file. This tool
helps to manage JAR files.
Javah – the C header and stub generator
Jdb- debugger
Java Buzzwords:
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features
which play an important role in the popularity of this language. The features of Java are also
known as java buzzwords.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
1.Object:
Object Definitions:
The new operator in java is used to create new objects of a class. A request will be sent to the
Heap Memory for object creation. If enough memory is available, the operator new initializes
the memory and returns the address of the newly allocated and initialized memory to the
object variable.
Declaration
Instantiation
Initialization
2. Class
Definition: A blueprint for creating objects that share similar properties (attributes)
and behaviors (methods). It defines the data structure (variables) and functionalities
(functions) of objects.
Class Name
----------
| attribute1 |
| attribute2 |
| ... |
----------
| method1( ) |
| method2( ) |
| ... |
----------
3. Inheritance
Person
----------
| attribute1 | (shared by all animals)
| attribute2 |
| ... |
----------
| method1( ) |
| method2( ) |
| ... |
----------
(inherits)
Employee (Subclass)
----------
| attribute3 | (specific to cats)
| ... |
----------
| calculatesalary( ) | (specific behavior)
| ... |
----------
4. Polymorphism
Definition: The ability of objects of different classes to respond differently to the
same method call. It allows for flexible and dynamic behavior.
method(argument)
/ \
/ \
SpecificClass1 SpecificClass2
| |
methodA(arg) methodB(arg) (different implementations)
5. Abstraction
Definition: The process of focusing on the essential details of an object while hiding
the underlying implementation details. It provides a simplified interface for users to
interact with objects without worrying about the internal workings.
Interface (Abstraction)
---------------------
| attribute1 (get/set) |
| attribute2 (get/set) |
| ... |
---------------------
| method1( ) |
| method2( ) |
| ... |
---------------------
(Implementation)
---------------------
| attribute1 (private) |
| attribute2 (private) |
| ... |
---------------------
| method1 implementation |
| method2 implementation |
| ... |
---------------------
6. Encapsulation
Definition: The process of bundling data (attributes) and the methods that operate on
that data within a single unit (class). It restricts direct access to data and promotes
controlled interaction through methods, ensuring data integrity and security.
Class Name
----------
| attribute1 (private) | (data hidden)
| attribute2 (private) |
| ... |
----------
| method1( ) (public) | (accesses data)
| method2( ) (public) |
| ... |
----------
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 is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
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).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine
o Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
The Just-In-Time (JIT) compiler is a component of the runtime environment that improves the
performance of Java™ applications by compiling bytecodes to native machine code at run time.
Distributed
Java is distributed because it facilitates users to create distributed applications over the internet.
RMI and EJB are used for creating distributed applications. This feature of Java makes us able
to access files by calling the methods from any machine on the internet.
Multi-threaded
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. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
Byte Code:
Java Byte Code is the language to which Java source is compiled and the Java Virtual Machine
understands. Unlike compiled languages that have to be specifically compiled for each different
type of computers, a Java program only needs to be converted to byte code once, after which
it can run on any platform for which a Java Virtual Machine exists.
Bytecode is the compiled format for Java programs. Once a Java program has been converted
to bytecode, it can be transferred across a network and executed by Java Virtual Machine
(JVM). Bytecode files generally have a .class extension. It is not normally necessary for a Java
programmer to know byte code, but it can be useful.
Execution Statements:
vi abc.java (to create a java file or open existing java file)
javac abc.java (java compiler – to convert java source code to byte code)
The Java Development Kit (JDK) is a software development environment used for developing
Java applications and applets. It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) and other tools needed in Java development.
JAVA RUNTIME ENVIRONMENT
JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.” The Java
Runtime Environment provides the minimum requirements for executing a Java application; it
consists of the Java Virtual Machine (JVM), core classes, and supporting files.
JDK – Java Development Kit (in short JDK) is Kit which provides the environment
to develop and execute (run) the Java program. JDK is a kit(or package) which includes two
things
Development Tools(to provide an environment to develop your java programs)
JRE (to execute your java program).
Note: JDK is only used by Java Developers.
JRE – Java Runtime Environment (to say JRE) is an installation package which provides
environment to only run (not develop) the java program (or application) onto your machine.
JRE is only used by them who only wants to run the Java Programs i.e. end users of your
system.
JVM – Java Virtual machine (JVM) is a very important part of both JDK and JRE because it
is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into
JVM and JVM is responsible for executing the java program line by line hence it is also known
as interpreter.
JRE consists of the following components:
Deployment technologies, including deployment, Java Web Start and Java Plug-in.
User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D,
Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input methods.
Integration libraries, including Interface Definition Language (IDL), Java Database
Connectivity (JDBC), Java Naming and Directory Interface (JNDI), Remote Method
Invocation (RMI), Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-
IIOP) and scripting.
Other base libraries, including international support, input/output (I/O), extension
mechanism, Beans, Java Management Extensions (JMX), Java Native Interface (JNI), Math,
Networking, Override Mechanism, Security, Serialization and Java for XML Processing
(XML JAXP).
Lang and util base libraries, including lang and util, management, versioning, zip,
instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging,
Preferences API, Ref Objects and Regular Expressions.
Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.
Interactions between JDK and JRE consider the following diagram:
Data types specify the different sizes and values that can be stored in the
variable. There are twotypes of data types in Java:
In Java language, primitive data types are the building blocks of data
manipulation. These are themost basic data types available in Java language.
// Relational Operators
System.out.println("\nRelational Operators:");
System.out.println("a == b: " + (a == b)); // Equal to
System.out.println("a != b: " + (a != b)); // Not equal to
System.out.println("a > b: " + (a > b)); // Greater than
System.out.println("a < b: " + (a < b)); // Less than
System.out.println("a >= b: " + (a >= b)); // Greater than or equal to
System.out.println("a <= b: " + (a <= b)); // Less than or equal to
// Logical Operators
boolean x = true;
boolean y = false;
System.out.println("\nLogical Operators:");
System.out.println("x && y: " + (x && y)); // Logical AND
System.out.println("x || y: " + (x || y)); // Logical OR
System.out.println("!x: " + (!x)); // Logical NOT
// Bitwise Operators
int m = 6; // 110 in binary
int n = 4; // 100 in binary
System.out.println("\nBitwise Operators:");
System.out.println("m & n: " + (m & n)); // Bitwise AND
System.out.println("m | n: " + (m | n)); // Bitwise OR
System.out.println("m ^ n: " + (m ^ n)); // Bitwise XOR
System.out.println("~m: " + (~m)); // Bitwise NOT
System.out.println("m << 1: " + (m << 1)); // Left shift
System.out.println("m >> 1: " + (m >> 1)); // Right shift
System.out.println("m >>> 1: " + (m >>> 1)); // Unsigned right shift
// Assignment Operators
System.out.println("\nAssignment Operators:");
int p = 10;
System.out.println("p = " + p);
p += 5;
System.out.println("p += 5: " + p);
p -= 3;
System.out.println("p -= 3: " + p);
p *= 2;
System.out.println("p *= 2: " + p);
p /= 4;
System.out.println("p /= 4: " + p);
p %= 3;
System.out.println("p %= 3: " + p);
// Conditional Operators
System.out.println("\nMiscellaneous Operators:");
// Conditional Operator
int q = (a > b) ? a : b;
System.out.println("Conditional (a > b) ? a : b: " + q);
// Unary Operators
System.out.println("\nUnary Operators:");
int u = 5;
System.out.println("u: " + u);
System.out.println("u++: " + (u++)); // Post-increment
System.out.println("u: " + u);
System.out.println("++u: " + (++u)); // Pre-increment
System.out.println("u--: " + (u--)); // Post-decrement
System.out.println("u: " + u);
System.out.println("--u: " + (--u)); // Pre-decrement
}
}
Arithmetic Operators:
a + b = 15
a-b=5
a * b = 50
a/b=2
a%b=0
Relational Operators:
a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false
Logical Operators:
x && y: false
x || y: true
!x: false
Bitwise Operators:
m & n: 4
m | n: 6
m ^ n: 2
~m: -7
m << 1: 12
m >> 1: 3
m >>> 1: 3
Assignment Operators:
p = 10
p += 5: 15
p -= 3: 12
p *= 2: 24
p /= 4: 6
p %= 3: 0
Miscellaneous Operators:
Conditional (a > b) ? a : b: 10
Type Comparison (a instanceof Integer): true
Unary Operators:
u: 5
u++: 5
u: 6
++u: 7
u--: 7
u: 6
--u: 5
Example Program:
package working;
public class SelectionStatementsExample {
// if-else statement
int num2 = 3;
if (num2 > 5) {
System.out.println("if-else statement: " + num2 + " is greater than 5");
} else {
System.out.println("if-else statement: " + num2 + " is not greater than 5");
}
// nested-if statement
int num3 = 7;
if (num3 > 5) {
if (num3 < 10) {
System.out.println("nested-if statement: " + num3 + " is greater than 5 and
less than 10");
}
}
// if-else-if statement
int num4 = 15;
if (num4 > 20) {
System.out.println("if-else-if statement: " + num4 + " is greater than 20");
} else if (num4 > 10) {
System.out.println("if-else-if statement: " + num4 + " is greater than 10 but
not greater than 20");
} else {
System.out.println("if-else-if statement: " + num4 + " is not greater than 10");
}
// switch-case statement
int day = 3;
switch (day) {
case 1:
System.out.println("switch-case statement: Sunday");
break;
case 2:
System.out.println("switch-case statement: Monday");
break;
case 3:
System.out.println("switch-case statement: Tuesday");
break;
case 4:
System.out.println("switch-case statement: Wednesday");
break;
case 5:
System.out.println("switch-case statement: Thursday");
break;
case 6:
System.out.println("switch-case statement: Friday");
break;
case 7:
System.out.println("switch-case statement: Saturday");
break;
default:
System.out.println("switch-case statement: Invalid day");
break;
}
// Demonstrating return
System.out.println("Demonstrating return statement:");
boolean shouldReturn = true;
if (shouldReturn) {
System.out.println("Returning early from main method");
return; // exits the main method early
}
VARIABLES:
Local Variables
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
Instance Variables:
Instance variables are non-static variables and are declared in a class outside of any method,
constructor, or block.
As instance variables are declared in a class, these variables are created when an object
of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier, then the default access specifier will be used.
Initialization of an instance variable is not mandatory. Its default value is dependent on
the data type of variable.
Instance variables can be accessed only by creating objects.
We initialize instance variables using constructors while creating an object.
class Student{
int id; //instance variables
String name; //instance variables
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Ram";
System.out.println (s1.id+" "+s1.name);
} }
Static Variables
These variables are declared similarly to instance variables. The difference is that static
variables are declared using the static keyword within a class outside of any method,
constructor, or block.
Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed automatically
when execution ends.
Initialization of a static variable is not mandatory. Its default value is dependent on the
data type of variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper
classes like Integer it is null, etc.
If we access a static variable like an instance variable (through an object), the compiler
will show a warning message, which won’t halt the program. The compiler will replace
the object name with the class name automatically.
If we access a static variable without the class name, the compiler will automatically
append the class name. But for accessing the static variable of a different class, we must
mention the class name as 2 different classes might have a static variable with the same
name.
Static variables cannot be declared locally inside an instance method.
Static blocks can be used to initialize static variables.
package working;
class test2
{
int x,y;
static int z; //only one copy of z variable is created
irrespective of any number of operators
void print()
{
System.out.println("the values of x is "+x);
System.out.println("the values of y is "+y);
System.out.println("the values of z is "+z);
}
}
// in the above program, t1.x,t1.y ,t2.x,t2.y have their own values but z
is common for t1,t2 ...
//(if t1.x will change its value t2.x will also change its value and vice
versa)
ARRAYS:
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.
int a[]={33,3,4,5};//declaration, instantiation and initialization
int a[]=new int[5];
int a[][[]=new int[3][3];
import java.util.Scanner;
}
for(int i=0;i<5;i++)
{
System.out.println(a[i]);
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
} }
Method Overloading:
class Adder{
static int add(int a, int b){return a+b;}
static int add(int a, int b, int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println (Adder.add(11,11));
System.out.println (Adder.add(11,11,11));
}}
Output: 22
33
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main (String[] args){
System.out.println (Adder.add(11,11));
System.out.println (Adder.add (12.3,12.6));
}}
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add (11,11)); //ambiguity
}}
Constructor:
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.
There are three types of constructors in Java: no-arg constructor, and parameterized
constructor, copy constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
package working;
class Box
{
double width,height,depth;
Box()
{
System.out.println("in constructor without args"+(width*height*depth));
}
Box(double x)
{
width=height=depth=x;
System.out.println("in constructor with one arg"+(width*height*depth));
}
Box(double x,double y,double z)
{
width=x;height=y;depth=z;
System.out.println("in constructor with one arg "+(width*height*depth));
}
}
public class constrcutorexample {
Output:
in constructor without args 0.0
in constructor with one arg 2.1839999999999997
in constructor with one arg 39.303999999999995
Types of Constructors:
Default Constructor:
A constructor that has no parameters is known as default constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler
does not create a default constructor. It is taken out. It is being overloaded and called
a parameterized constructor.
Class Employee ()
{
String name,dept;
void Employee ()
{
Name=”abc”;
Dept=”HRD”;
System.out.println (“name is “+name+”dept is”+dept);
}}
In the above program , default constructor is created with no arguments and no statements
inside the constructor.
Parameterized Constructor:
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Copy Constructor
package working;
class Box
{
double width,height,depth;
This keyword:
class Student{
int usn;
String name;
float avg;
Student (int usn, String name, float avg){
this.usn=usn;
this.name=name;
this.avg=avg;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"abcd",5000f);
Student s2=new Student(112,"defg",6000f);
s1.display();
s2.display();
}}
In the above program formal arguments and instance variables are same, hence this
keyword is used , this.usn, this.name , this.avg represents instance variables.
If local variables(formal arguments) and instance variables are different, there is no
need to use this keyword
This keyword is used to Call default constructor from parameterized constructor and
vice versa.
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}