0% found this document useful (0 votes)
23 views

22cds42-Module-1-Notes-updated

This document provides an overview of Java, including its history, features, and components such as the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). It explains key concepts of object-oriented programming, data types, and the significance of Java's portability and security. Additionally, it outlines the structure of classes and objects, inheritance, polymorphism, and other fundamental principles of Java programming.

Uploaded by

Akash Kengua
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)
23 views

22cds42-Module-1-Notes-updated

This document provides an overview of Java, including its history, features, and components such as the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). It explains key concepts of object-oriented programming, data types, and the significance of Java's portability and security. Additionally, it outlines the structure of classes and objects, inheritance, polymorphism, and other fundamental principles of Java programming.

Uploaded by

Akash Kengua
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/ 28

MODULE-1:

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.

The Java Language:

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

Java Development Kit (JDK):

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.

A list of most important features of Java language is given below.

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

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

1.Object:

An object is an instance of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Declaring object in Java

Class-name object name = new Class-name ( );

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.

This is used to operate 3 different operations in java.

 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

 Definition: A mechanism in object-oriented programming that allows creating new


classes (subclasses) based on existing classes (super classes). Subclasses inherit
properties and behaviors from the superclass, and can add their own specializations.

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

Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java 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)

java abc ( java interpreter – to interpret results from bytecode)

Sample bytecode file ( Class File)

JVM , JRE and Java environment:

JAVA DEVELOPMENT KIT:

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.

JAVA VIRTUAL MACHINE


It is:
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
An implementation is a computer program that meets the requirements of the JVM
specification
Runtime Instance Whenever you write java command on the command prompt to run the java
class, an instance of JVM is created.
Difference between JDK, JRE and JVM:

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:

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,and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data
manipulation. These are themost basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared


before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:


boolean data type Boolean one = only two possible values: true and false
false
byte data type byte a = 10, byte 8-bit signed two's complement , Its
b = -20 value-range lies between -128 to 127
int data type int a=20 32-bit signed two's complement integer.
Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647
(2^31 -1).
char data type char letterA = 'A' The char data type is a single 16-bit
Unicode character
short data type short s = 10000 short data type is a 16-bit signed two's
complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive).
long data type long a = 100000L The long data type is a 64-bit two's
complement integer. Its value-range lies
between - 9,223,372,036,854,775,808(-
2^63) to
9,223,372,036,854,775,807(2^63 -
1)(inclusive).

float data type float f1 = 234.5f single-precision 32-bit IEEE 754


floating point
double data type double d1 = 12.3 double-precision 64-bit IEEE 754
floating point

Types of Operator in Java


1) Basic Arithmetic Operators – (+, -, *, /, %)
2) Assignment Operators (=, +=, -=, *=, /=, %=)
3) Auto-increment and Auto-decrement Operators (++,--)
4) Logical Operators (&&, || !)
5) Comparison (relational) operators (= =,! =, >, <, >=, <=)
6) Bitwise Operators (&, |, ^, ~, <<, >>)
7) Ternary Operator (num2 = (num1 == 25) ? 100: 200;)
package working;

public class OperatorExamples {


public static void main(String[] args) {
// Arithmetic Operators
int a = 10;
int b = 5;
System.out.println("Arithmetic Operators:");
System.out.println("a + b = " + (a + b)); // Addition
System.out.println("a - b = " + (a - b)); // Subtraction
System.out.println("a * b = " + (a * b)); // Multiplication
System.out.println("a / b = " + (a / b)); // Division
System.out.println("a % b = " + (a % b)); // Modulus

// 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);

// Type Comparison Operator


System.out.println("Type Comparison (a instanceof Integer): " + ((Object)a instanceof
Integer));

// 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

Java’s Selection statements:


if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return

Example Program:

package working;
public class SelectionStatementsExample {

public static void main(String[] args) {


// if statement
int num1 = 10;
if (num1 > 5) {
System.out.println("if statement: " + num1 + " is greater than 5");
}

// 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 break, continue, and return in loops


System.out.println("Loop with break and continue:");
for (int i = 1; i <= 5; i++) {
if (i == 3) {
System.out.println("continue: Skipping number " + i);
continue; // skips the rest of the loop body when i is 3
}
if (i == 5) {
System.out.println("break: Breaking the loop at number " + i);
break; // exits the loop when i is 5
}
System.out.println("Current number: " + i);
}

// 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
}

// This part will not be reached if shouldReturn is true


System.out.println ("This message will not be printed if shouldReturn is true.");
}
}

if statement: 10 is greater than 5


if-else statement: 3 is not greater than 5
nested-if statement: 7 is greater than 5 and less than 10
if-else-if statement: 15 is greater than 10 but not greater than 20
switch-case statement: Tuesday
Loop with break and continue:
Current number: 1
Current number: 2
continue: Skipping number 3
Current number: 4
break: Breaking the loop at number 5
Demonstrating return statement:
Returning early from main method

VARIABLES:

Local Variables

A variable defined within a block or method or constructor is called a local variable.


 These variables are created when the block is entered, or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
 Initialization of the local variable is mandatory before using it in the defined scope.

import java.io.*;

class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


System.out.println("Local Variable: " + var);
}
}

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);
}
}

public class staticexample {


public static void main(String args[])
{
test2 t1=new test2();
test2 t2=new test2();
t1.x=20;t1.y=23;t1.z=80;
t1.print();
t2.x=200;t2.y=230;t2.z=800;
t2.print();
t1.print();
}
}

// 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;

public class Test1 {


public static void main(String args[])
{
int a1[]=new int[5];
int a[][]=new int[3][3];
Scanner s=new Scanner(System.in);
//reading values and printing values of single dimensional array
for(int i=0;i<5;i++)
{
a1[i]=s.nextInt();

}
for(int i=0;i<5;i++)
{
System.out.println(a[i]);

//reading values and printing values of double dimensional array


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a[i][j]=s.nextInt();
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}
}

Command line Arguments:


 The java command-line argument is an argument i.e. passed at the time of running the
java program.
 The arguments passed from the console can be received in the java program and it can be
used as an input.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}

1. compile by > javac CommandLineExample.java


2. run by > java CommandLineExample welcome

Output: Your first argument is: welcome

class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);
} }

1. compile by > javac A.java


2. run by > java A abc def 1 3 abc
Output: abc
def
1
3
abc

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
}}

Compile Time Error: method add(int,int) is already defined in class Adder

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.

Rules for creating Java constructor:


 Constructor name must be the same as its class name.
 A Constructor must have no explicit return type.
 A Java constructor cannot be abstract, static, final, and synchronized

Example for Constructor and Constructor Overloading:

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 {

public static void main(String[] args) {

Box b1=new Box(); //invokes Box()


Box b2=new Box(1.2,1.3,1.4); //invokes Box(double x,double double z)
Box b3=new Box(3.4); //invokes Box(double x)
}

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;

Box(double x,double y,double z)


{
width=x;height=y;depth=z;
System.out.println("In Box(double x,double y,double z) , Volume
is"+(width*height*depth));
}
Box(Box b)
{
width=b.width;
height=b.height;
depth=b.depth;
System.out.println("in Box(Box b) , Volume is"+(width*height*depth));
}
}
public class constrcutorexample {
public static void main(String[] args) {

Box b1=new Box(3.4,1.1,2.1); //invokes Box(double x)


Box b2=new Box(b1);
}}
OUPUT:

In Box (double x, double y, double z), Volume is7.854000000000001


in Box (Box b), Volume is7.854000000000001

This keyword:

 Used to refer the current instance.


 If local variables (formal arguments) and instance variables are same “this” is used to
refer to the current instance or object.

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();
}}

You might also like