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

Java Unit-1

The document discusses Java programming language. It defines Java, its applications and features. It describes the Java Virtual Machine, its components and how it works. It also discusses Java naming conventions and basic data types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Java Unit-1

The document discusses Java programming language. It defines Java, its applications and features. It describes the Java Virtual Machine, its components and how it works. It also discusses Java naming conventions and basic data types.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Unit-1

1.Introduction to java:
What is Java

Java is a high Level programming language and it is also called as a platform. Java is a
secured and robust high level object-oriented programming language. Platform: Any software
or hardware environment in which a program runs is known as a platform. Java has its own
runtime environment (JRE) and API so java is also called as platform. Java fallows the
concept of Write Once, Run Anywhere.

Application of java

1. Desktop Applications

2. Web Applications

3. Mobile

4. Enterprise Applications

5. Smart Card

6. Embedded System

7. Games

8. Robotics etc

2.FEATURES OF JAVA:

 Object Oriented – Java implements basic concepts of Object oriented programming


System (OOPS) ie Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation. In
Java, everything is an Object. Java can be easily extended since it is based on the Object
model.

 Platform Independent − Unlike many other programming languages including C and


C++, when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and interpreted by
the Virtual Machine (JVM) on whichever platform it is being run on

.  Simple – Java fallows the basic Syntax of C,C++. If you understand the basic concept of
OOPS then it is easy to master in java.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on publickey encryption

.  Architecture-neutral − Java compiler generates an architectureneutral object file format,


which makes the compiled code executable on many processors, with the presence of Java
runtime system.

 Portable − Being architecture-neutral and having no implementation dependent aspects of


the specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.

 Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.

 Multithreaded − With Java's multithreaded feature In java we can write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.

 Interpreted − Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the linking
is an incremental and light-weight process.

 High Performance − With the use of Just-In-Time compilers, Java enables high
performance.

 Distributed − Java is designed for the distributed environment of the internet.

 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to


adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

3.The java virtual mechine:


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e.
JVM is platform dependent).

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

2. An implementation Its implementation is known as JRE (Java Runtime Environment).

3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of
JVM is created.

The JVM performs following operation:


 Loads code

 Verifies code

 Executes code

 Provides runtime environment

Classloader : Classloader is a subsystem of JVM which is used to load class files.


Whenever we run the java program, it is loaded first by the classloader

Method area: In the method area, all class level information like class name, immediate
parent class name, methods and variables information etc. are stored, including static
variables. There is only one method area per JVM, and it is a shared resource.
Heap area: Information of all objects is stored in the heap area. There is also one Heap
Area per JVM. It is also a shared resource.
Stack area: For every thread, JVM creates one run-time stack which is stored here. Every
block of this stack is called activation record/stack frame which stores methods calls. All
local variables of that method are stored in their corresponding frame. After a thread
terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.
PC Registers: Store address of current execution instruction of a thread. Obviously, each
thread has separate PC Registers.
Native method stacks: For every thread, a separate native stack is created. It stores native
method information.
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions.
Java Native Interface (JNI) :
It is an interface that interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to
be called by C/C++ libraries which may be specific to hardware.
Native Method Libraries :
It is a collection of the Native Libraries(C, C++) which are required by the Execution
Engine.

4.Naming conventions in java:

Identifiers Naming Rules Examples


Type

Class It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button, {
System, Thread, etc. //code snippet
Use appropriate words, instead of }
acronyms.

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as {
Runnable, Remote, ActionListener. //code snippet
Use appropriate words, instead of }
acronyms.

Method It should start with lowercase letter. class Employee


It should be a verb such as main(), print(), {
println(). // method
If the name contains multiple words, start void draw()
it with a lowercase letter followed by an {
uppercase letter such as //code snippet
actionPerformed(). }
}

Variable It should start with a lowercase letter such class Employee


as id, name. {
It should not start with the special // variable
characters like & (ampersand), $ (dollar), int id;
_ (underscore). //code snippet
If the name contains multiple words, start }
it with the lowercase letter followed by an
uppercase letter such as firstName,
lastName.
Avoid using one-character variables such
as x, y, z.

Package It should be a lowercase letter such as //package


java, lang. package com.javatpoint;
If the name contains multiple words, it class Employee
should be separated by dots (.) such as {
java.util, java.lang. //code snippet
}

Constant It should be in uppercase letters such as class Employee


RED, YELLOW. {
If the name contains multiple words, it //constant
should be separated by an underscore(_) static final
such as MAX_PRIORITY. int MIN_AGE = 18;
It may contain digits but not as the first //code snippet
letter. }

*CamelCase in Java naming conventions:

Java follows camel-case syntax for naming the class, interface, method, and variable.

If the name is combined with two words, the second word will start with uppercase letter
always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.

5.Datatypes in java:

There are two data types available in Java –

 Primitive Data Types

 Non Primitive Types

Primitive Data Types


There are eight primitive data types supported by Java. Primitive data types are predefined by
the language and named by a keyword. Let us now look into the eight primitive data types in
detail.

Byte:

 Byte data type is an 8-bit signed two's complement integer

 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an integer.

Short:

 Short data type is a 16-bit signed two's complement integer

 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer

Int:

 Int data type is a 32-bit signed two's complement integer


 Integer is generally used as the default data type for integral values unless there is a
concern about memory

Long:

 Long data type is a 64-bit signed two's complement integer

 This type is used when a wider range than int is needed

Float:

Float data type is a single-precision 32-bit IEEE 754 floating point

 Float is mainly used to save memory in large arrays of floating point numbers

Double

 double data type is a double-precision 64-bit IEEE 754 floating point

 This data type is generally used as the default data type for decimal values, generally the
default choice

Boolean:

 boolean data type represents one bit of information

 There are only two possible values: true and false


 This data type is used for simple flags that track true/false conditions.

Char:

 char data type is a single 16-bit Unicode character

 Char data type is used to store any character.

Non-Primitive Data Types

Non-primitive data types or reference data types refer to instances or objects. They cannot
store the value of a variable directly in memory. They store a memory address of the
variable. Unlike primitive data types we define by Java, non-primitive data types are user-
defined.

Array

An array holds elements of the same type. It is an object in Java, and the array name (used for
declaration) is a reference value that carries the base address of the continuous location of
elements of an array

String

The String data type stores a sequence or array of characters. A string is a non-primitive data
type, but it is predefined in Java. String literals are enclosed in double quotes.

Interface

An interface is declared like a class. The key difference is that the interface contains abstract
methods by default; they have nobody.

Enum

An enum, similar to a class, has attributes and methods. However, unlike classes, enum
constants are public, static, and final (unchangeable – cannot be overridden). Developers
cannot use an enum to create objects, and it cannot extend other classes. But, the enum can
implement interfaces.

// Java Program to Demonstrate Primitive Data Type

class sample {

public static void main(String args[])

{
char a = 'G';

int i = 89;

byte b = 4;

short s = 56;

double d = 4.355453532;

float f = 4.7333434f;

long l = 12121;

System.out.println("char: " + a);

System.out.println("integer: " + i);

System.out.println("byte: " + b);

System.out.println("short: " + s);

System.out.println("float: " + f);

System.out.println("double: " + d);

System.out.println("long: " + l);

Output;

char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Java Keywords:
Java Keywords can not be used as a variable name.
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

6.Control statements:

Java provides three types of control flow statements.

1. Selection /(Decision Making) statements


o if
o if-else
o if-else-if
o nested if
o switch case statement
2. Loop statements/ Iterative statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
o return

7.Selection statements:
1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

Example:

public class Student {

public static void main(String[] args) {

int x = 10;

int y = 12;

if(x+y > 20) {

System.out.println("x + y is greater than 20");

} }

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.

Syntax:

if(condition) {

statement 1; //executes when condition is true

else{

statement 2; //executes when condition is false

Consider the following example.

public class Student {


public static void main(String[] args) {

int x = 10;

int y = 12;

if(x+y < 10) {

System.out.println("x + y is less than 10");

} else {

System.out.println("x + y is greater than 20");

}}

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true.

Syntax :

if(condition 1) {

statement 1; //executes when condition 1 is true

else if(condition 2) {

statement 2; //executes when condition 2 is true

else {

statement 2; //executes when all the conditions are false

Example:

public class Student {

public static void main(String[] args) {


String city = "Delhi";

if(city == "Meerut") {

System.out.println("city is meerut");

}else if (city == "Noida") {

System.out.println("city is noida");

}else if(city == "Agra") {

System.out.println("city is agra");

}else {

System.out.println(city);

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.

Syntax

if(condition 1) {

statement 1;

if(condition 2) {

statement 2;

else{

statement 2;

example.
public class Student {

public static void main(String[] args) {

String address = "Delhi, India";

if(address.endsWith("India")) {

if(address.contains("Meerut")) {

System.out.println("Your city is Meerut");

}else if(address.contains("Noida")) {

System.out.println("Your city is Noida");

}else {

System.out.println(address.split(",")[0]);

}else {

System.out.println("You are not living in India");

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable
which is being switched. The switch statement is easier to use instead of if-else-if statements.
It also enhances the readability of the program.

The syntax.

switch (expression){

case value1:

statement1;

break;
.

case valueN:

statementN;

break;

default:

default statement;
}

Example:

public class Sample

public static void main(String[] args) {

int k=20;

switch(k)

case 1:

System.out.println("1");

break;

case 2:

System.out.println("2");

break;

case 3:

System.out.println("3");

break;

default: System.out.println("Not in 1, 2 or 3");


}

Iterative statements:

For Loop

The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.

Syntax:

for(initialization;condition;incr/decr){

//code to be executed

Example:

public class Sample {

public static void main(String[] args) {

for(int i=1;i<=20;i++){

System.out.println(i);

While Loop

The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.

Syntax:

1. while(condition){

2. //code to be executed
3. }

1. public class Sample {

2. public static void main(String[] args) {

3. int j=1;

4. while(j<=10){

5. System.out.println(j);

6. j++;

7. }

8. } }

do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.The Java do-while loop is executed at least once because condition is
checked after loop body.

Syntax:

do{

//code to be executed

}while(condition);

Example:

public class Example {

public static void main(String[] args) {

int j=1;

do{ System.out.println(j);

j++;

}while(j<=10);

}}
Break Statement

The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.

Example:

1. public class Simple {

2. public static void main(String[] args) {

3. for(int i=1;i<=10;i++){

4. if(i==5){

5. break;

6. }

7. System.out.println(i);

8. }

9. }

10. }

Continue Statement

The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

Example:

1. public class Sample {

2. public static void main(String[] args) {

3. for(int k=1;k<=10;k++){

4. if(k==5){

5. continue;

6. }

7. System.out.println(k);
8. }

9. }

10. }

Return statement:

The purpose of using a Return statement is to terminate the current method of execution and
transfer the control to the next "calling method".

There are two types of Return statements, which are "Return with a value" and "Return
without a value".

Example:

class continue_statement

public static void main(String[] args)

int age = 12;

System.out.println("Using Return");

if (age<18)

return; //terminates the method

System.out.println("Will not get executed!");

8.Arrays in java:
1. Normally, an array is a collection of similar type of elements which has contiguous
memory location.
2. 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
3. Array in Java is index-based, the first element of the array is stored at the 0th index, 2 nd
element is stored on 1st index and so on i.e. Arrays in Java are 0 base indexed.

Declaring Array Variables

Syntax :

dataType arrayRefVar[];

Example :

double myList[];

Advantages

● Code Optimization: It makes the code optimized, we can retrieve or sort the data

efficiently.

● Random access: We can get any data located at an index position.

Disadvantages

● Size Limit: We can store only the fixed size of elements in the array. It doesn't

grow its size at runtime. To solve this problem, collection framework is used in

Java which grows automatically.

Types of Array in java

There are two types of array.

 Single Dimensional Array


 Two Dimensional Array
 Three Dimensional Array(3d Array)

Single Dimensional Array

Syntax to Declare an Array in Java

dataType arr[];

Instantiation of an Array

arrayRefVar = new datatype[size];

Declaration, Instantiation and Initialization of Java Array


Exampe:1

class Main{

public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization

a[1]=20;

a[2]=70;

a[3]=40;

a[4]=50;

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

}}

Example:2

public class TestArray {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements

for (int i = 0; i < myList.length; i++) {

System.out.println(myList[i] + " ");

// Summing all elements

double total = 0;

for (int i = 0; i < myList.length; i++) {

total += myList[i];

} System.out.println("Total is "

+
total);

// Finding the largest element

double max = myList[0];

for (int i = 1; i < myList.length; i++) {

if (myList[i] > max) max = myList[i];

} System.out.println("Max is "

max);

Multidimensional Array

In such case, data is stored in row and column based index (also known as matrix

form).

Syntax:

dataType arrayRefVar[][];

Example:

int arr[][]=new int[3][3];

Example of Matrix:

arr[0][0]=1;

arr[0][1]=2;

arr[0][2]=3;

arr[1][0]=4;

arr[1][1]=5;

arr[1][2]=6;

arr[2][0]=7;

arr[2][1]=8;
arr[2][2]=9;

Example:

//Java Program to illustrate the use of multidimensional array

class Testarray3{

public static void main(String args[]){

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(arr[i][j]+" ");

System.out.println();

}}

3D Array:

3-D arrays are referred to as multi-dimensional arrays. Multi-dimensional arrays are


defined as an “array of arrays” that store data in a tabular form.

A 3-D array can be declared as follows:

int arr[4][5][8];

This array can store a total of 4 X 5 X 8 = 160 elements.

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

int arr[][][] = {
{ {0,1,2}, {2,3,4}, {6,7,1} },
{ {6,7, 1}, {8,9, 2}, {9,14, 22} }
};
System.out.println(arr[0][0][0]);

for (int i = 0; i < 2; ++i)


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 3; ++k)
{

System.out.println("Element at arr[" + i + "][" + j


+ "][" + k + "] = " + arr[i][j][k]);

}
}
}
}
}

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.
 So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
 The users can pass the arguments during the execution bypassing the command-line
arguments inside the main() method.

Example:

class A{

public static void main(String args[]){

for(int i=0;i<args.length;i++)

System.out.println(args[i]);

Passing values by command prompt

compile by > javac A.java

run by > java A Bhanu 25.8 1 3 abc

output:
Bhanu

25.8

abc
Unit-2

1.Strings:
A Java string is a sequence of characters that exists as an object of the class java.lang. Java
strings are created and manipulated through the string class. Once created, a string is
immutable -- its value cannot be changed.

2.Creating a Java string:


There are two was to creating a string in java:

1.String literal.

2. Uning new keyword.

1.String literal:

1. Java String literal is created by using double quotes.

String s="welcome";

2. Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is created and placed in the
pool.

String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

3. In the above example, only one object will be created. Firstly, JVM will not find any
string object with the value "Welcome" in string constant pool that is why it will create
a new object. After that it will find the string with the value "Welcome" in the pool, it
will not create a new object but will return the reference to the same instance.

2.Using new keyword:

String s=new String("Welcome");

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Example:

public class StringExample{

public static void main(String args[]){

String s1="java";//creating string by Java string literal

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);//converting char array to string

String s3=new String("example");//creating Java string by new keyword

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

}}

3.String class Methods


1. int length(): Returns the number of characters in the String.
"Programming".length(); // returns 11
2 Char charAt(int i): Returns the character at ith index.
" Programming ".charAt(3); // returns ‘g’

3 String substring (int i): Return the substring from the ith index character to end.
" Programming".substring(3); // returns “gramming”
4 String substring (int i, int j): Returns the substring from i to j-1 index.

" Programming".substring(2, 5); // returns “ogr”


5 String concat( String str): Concatenates specified string to the end of this string.

String s1 = ”hello”;
String s2 = ”world”;
String output = s1.concat(s2); // returns “helloworld”
6 int indexOf (String s): Returns the index within the string of the first occurrence of the
specified string.

String s = ”Learn Share Learn”;


int output = s.indexOf(“Share”); // returns 6
7 int indexOf (String s, int i): Returns the index within the string of the first occurrence of
the specified string, starting at

the specified index.

String s = ”Learn Share Learn”;


int output = s.indexOf("ea",3);// returns 13
8 Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the
specified string.

String s = ”Learn Share Learn”;


int output = s.lastIndexOf("a"); // returns 14
9 boolean equals( Object otherObj): Compares this string to the specified object.

Boolean out = “Geeks”.equals(“Geeks”); // returns true


Boolean out = “Geeks”.equals(“geeks”); // returns false
10 boolean equalsIgnoreCase (String anotherString): Compares string to another string,
ignoring case considerations.

Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true


Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

11 int compareTo( String anotherString): Compares two string lexicographically.

int out = s1.compareTo(s2); // where s1 and s2 are


// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
12 int compareToIgnoreCase( String anotherString): Compares two string
lexicographically, ignoring case

considerations.

int out = s1.compareToIgnoreCase(s2);


// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
13 String toLowerCase(): Converts all the characters in the String to lower case.

String word1 = “HeLLo”;


String word3 = word1.toLowerCase(); // returns “hello"
14 String toUpperCase(): Converts all the characters in the String to upper case.

String word1 = “HeLLo”;


String word2 = word1.toUpperCase(); // returns “HELLO”
15 String trim(): Returns the copy of the String, by removing whitespaces at both ends. It
does not affect whitespaces in

the middle.

String word1 = “ Learn Share Learn “;


String word2 = word1.trim(); // returns “Learn Share Learn”
16 String replace (char oldChar, char newChar): Returns new string by replacing all
occurrences

of oldChar with newChar.


String s1 = “programming“;
String s2 = s1.replace(‘m’ ,’g’); // returns “progragging”
4.String comparision in java:

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

1.By using equals() method

The String class equals() method compares the original content of the string. It compares
values of string for equality.

class Teststringcomparison1{

public static void main(String args[]){

String s1="Sachin";

String s2="Sachin";

String s3=new String("Sachin");

String s4="Saurav";

System.out.println(s1.equals(s2));//true

System.out.println(s1.equals(s3));//true

System.out.println(s1.equals(s4));//false

3.By using == operator:

The double equal (==) operator compares two objects references to check whether
they refer to same instance. This also will return true on successful match else returns false.

Example:

class Teststringcomparison3{

public static void main(String args[]){


String s1="Sachin";

String s2="Sachin";

String s3=new String("Sachin");

System.out.println(s1==s2);//true

System.out.println(s1==s3);//false

} }

3.By using compareTo() method:

The String class compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

s1 == s2 : The method returns 0.

s1 > s2 : The method returns a positive value.

s1 < s2 : The method returns a negative value.

Example:

class Teststringcomparison4{

public static void main(String args[]){

String s1="hello";

String s2="Hello";

System.out.println(s1.compareTo(s2)); //32(s1>s2)

System.out.println(s2.compareTo(s1)); //-32(s1<s2)

5.Procedural Programming:
Procedural Programming can be defined as a programming model which is derived from structured
programming, based upon the concept of calling procedure. Procedures, also known as routines,
subroutines or functions, simply consist of a series of computational steps to be carried out.
During a program’s execution, any given procedure might be called at any point, including by
other procedures or itself.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL,
BASIC, Pascal and C.
Advantages of Procedural Programming

 It is good for general-purpose programming.


 We can access the same code at different points in the software program without
repeating it.
 The memory need is also reduced by using the Procedural Programming technique.

Disadvantages of Procedural Programming

 The code reusability feature is not present in procedural-oriented programming. We


have to rewrite the same programming code many times.
 Difficult to relate to real-world objects.
 We can not perform operations like encapsulation, inheritance, etc.

Differences between c++ and java


Features C++ Java

Platform Independence Platform-dependent Platform-independent


Interpreter and Compiler Compiled programming language Compiled and interpreted language
Portability Not portable Portable

Memory Management Manual System-controlled


Multiple Inheritance Supports single inheritance and Only supports single inheritance
multiple inheritance

Overloading Both operators and methods can be Allows only method overloading
overloaded

Compatibility with Other Compatible with C Not compatible with any language
Programming Languages
Pointers Supports pointers Supports pointers with restrictions
Documentation Comment Does not support documentation Has built-in documentation comments
comments support (/**…**/), allowing Java files
to have their own documentation
Thread Support Does not support thread Has built-in thread support via the
“thread” class

Difference between c and java


COMPARISON Difference between c and java Java
PARAMETER C
Developed by The C programming language was Java was developed by James Gosling at
developed by Dennis M. Ritchie in Sun Microsystems. Now, it is owned by
1972. Oracle.

Programming model C is a procedural programming language Java is an object-oriented programming


language.

Platform dependence C is platform-dependent. It is based on Java is platform-independent. It is based


the concept of Write Once Compile on the concept of Write Once Run
Anywhere. Anywhere.

Type of language C is a middle-level language as it binds Java is a high-level language as the


the bridges between machine-level and translation of Java code takes place into
high-level languages. machine language, using a compiler or
interpreter.

Compilation and Interpretation C is only compiled and not interpreted. Java is both compiled and interpreted.
Pointers C has support for pointers. Java does not support pointers.
Threading C is not intrinsically a multithreaded Java supports threading.
language; however, there are many
libraries that add threading functionality.
Garbage Collection In C, Garbage Collection needs to be In Java, Garbage Collector
done manually. automatically does the Garbage
Collection.

Memory Allocation In order to do memory allocation in C, In order to do memory allocation in


functions like malloc(), calloc(), etc. can Java, the ‘new’ keyword can be used.
be used. But there is no ‘new’ keyword
in C.
Support for call by reference C has support for both call by value and Java has support for the only call by
call by reference. value.

Application The C programming language is used Java can be used only for Application
for both system programming as well as programming and not for system
Application programming. programming.

Functional Units In C, mostly the functional units are In Java, mostly the functional units are
functions as it is a procedural objects as it is an object-oriented
programming language. programming language.

What Is Object-Oriented Programming (OOP)?


As the name suggests, objects in programming. A programming model is
based upon the concepts of objects, or where everything is represented as an object.
In OOP, we try to see the whole world as an object. For example, dogs have states
or data members like color, hungry, and breed, and the behaviors or methods
(actions they can perform) are barking, wagging their tail, eating, sleeping, etc.

5.Java Methods

The method in Java or Methods of Java is a collection of statements that perform some
specific task and return the result to the caller. A Java method can perform some
specific task without returning anything. Java Methods allow us to reuse the code
without retyping the code. In Java, every method must be part of some class that is
different from languages like C, C++, and Python.
1. A method is like a function i.e. used to expose the behavior of an object.
2. It is a set of codes that perform a particular task.
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed
in your application. In Java, there 4 types of access specifiers.
 public: It is accessible in all classes in your application.
 protected: It is accessible within the class in which it is defined and in its
subclass/es
 private: It is accessible only within the class in which it is defined.
 default: It is declared/defined without using any modifier. It is accessible within the
same class and package within which its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the method or void if does
not return a value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded
by their data type, within the enclosed parenthesis. If there are no parameters, you must
use empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations. It is Optional in syntax.

Types of Methods in Java


There are two types of methods in Java:

1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point.

2. User-defined Method

The method written by the user or programmer is known as a user-defined method.


These methods are modified according to the requirement.
1. Instance Method: Access the instance data using the object name.Declared inside a
class.

Syntax:

// Instance Method

void method_name(){

body // instance area

import java.io.*;

// Different class

class class1 {

// Instance method in different class

void add()

int a= 2;

int b= 3;
System.out.println("The sum of 2 and 3 is :" + (a+b));

class GFG {

// Static method

public static void main (String[] args) {

// creating object of the class

class1 obj = new class1();

// calling instance method

obj.add();

System.out.println("GFG!");

Static Method in Java


The static keyword is used to construct methods that will exist regardless of whether or
not any instances of the class are generated. Any method that uses the static keyword is
referred to as a static method.
Features of static method:

 A static method in Java is a method that is part of a class rather than an instance of
that class.
 Every instance of a class has access to the method.
 Static methods have access to class variables (static variables) without using the
class’s object (instance).
 Only static data may be accessed by a static method. It is unable to access data that
is not static (instance variables).
 In both static and non-static methods, static methods can be accessed directly.
Syntax to declare the static method:

Access_modifier static void methodName()


{ // Method body.}

The name of the class can be used to invoke or access static methods.
Syntax to call a static method:
className.methodName();
The static method does not have access to the instance variable
The JVM runs the static method first, followed by the creation of class instances.
Because no objects are accessible when the static method is used. A static method does
not have access to instance variables. As a result, a static method can’t access a class’s
instance variable.

import java.io.*;

public class GFG {

// static variable

static int a = 40;

// instance variable

int b = 50;

void simpleDisplay()

System.out.println(a);

System.out.println(b);
}

// Declaration of a static method.

static void staticDisplay()

System.out.println(a);

// main method

public static void main(String[] args)

GFG obj = new GFG();

obj.simpleDisplay();

// Calling static method.

staticDisplay();

Difference Between the static method and instance method

Instance Methods Static Methods


Instance Methods Static Methods

It requires an object of the class. It doesn’t require an object of the class.

It can access only the static attribute of a


It can access all attributes of a class.
class.

The methods can be accessed only using The method is only accessed by class
object reference. name.

Syntax: Objref.methodname() Syntax: className.methodname()

It’s an example of pass-by-value It is an example of pass-by-reference


programming. programming.

Static Block
In simpler language whenever we use a static keyword and associate it to a block then
that block is referred to as a static block. This code inside the static block is executed
only once: the first time the class is loaded into memory. So in order to call any static
block, there is no specified way as static block executes automatically when the class is
loaded in memory.

class Test {

// Case 1: Static variable

static int i;

// Case 2: non-static variables

int j;
// Case 3: Static block

// Start of static block

static

i = 10;

System.out.println("static block called ");

// End of static block

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String args[])

// Although we don't have an object of Test, static

// block is called because i is being accessed in

// following statement.

System.out.println(Test.i);

}
Arrays to methods
import java.util.Scanner;

public class ArraysToMethod {


public int max(int [] array) {
int max = 0;

for(int i=0; i<array.length; i++ ) {


if(array[i]>max) {
max = array[i];
}
}
return max;
}

public int min(int [] array) {


int min = array[0];

for(int i = 0; i<array.length; i++ ) {


if(array[i]<min) {
min = array[i];
}
}
return min;
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");

for(int i=0; i<size; i++) {


myArray[i] = sc.nextInt();
}
ArraysToMethod m = new ArraysToMethod();
System.out.println("Maximum value in the array is::"+m.max(myArray));
System.out.println("Minimum value in the array is::"+m.min(myArray));
}
}

Recursion in Java:
In Java, Recursion is a process in which a function calls itself directly or indirectly is
called recursion and the corresponding function is called a recursive function.

class GFG

// recursive method

int fact(int n)

int result;

if (n == 1)

return 1;

result = fact(n - 1) * n;

return result;
}

class Recursion {

public static void main(String[] args)

GFG f = new GFG();

System.out.println("Factorial of 3 is "

+ f.fact(3));

System.out.println("Factorial of 4 is "

+ f.fact(4));

System.out.println("Factorial of 5 is "

+ f.fact(5));

‘this’ reference in Java


In Java, ‘this’ is a reference variable that refers to the current object, or can be said
“this” in Java is a keyword that refers to the current object instance. It can be used to
call current class methods and fields, to pass an instance of the current class as a
parameter, and to differentiate between the local and instance variables. Using “this”
reference can improve code readability and reduce naming conflicts.
class Test

int a;

int b;

// Parameterized constructor

Test(int a, int b)

this.a = a;

this.b = b;

void display()

// Displaying value of variables a and b

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

public static void main(String[] args)

Test object = new Test(10, 20);

object.display();

}
}

6.Basic Object-Oriented Programming (OOPS)Concept

Object:

An object which is an entity with some characteristics and behavior or anything


that exists physically in the world, like a dog, a pen, a pencil, etc. An object is an
instance of the class. In Object-Oriented Programming, when a class is
defined, no memory is allocated, but when an object is created, the memory is
allocated.

Class:

A class is a blueprint of the object. When you define a class, you define a
blueprint for an object. A class contains data members (variables) and member
functions.

Encapsulation:

Encapsulation means encapsulating (binding or wrapping) code and data into a


single unit. More technically, encapsulation means placing the data and the
functions that work on that data in a single place. Like, a capsule is wrapped with
different medicines.
For example the balance variable as private to protect your account and ensure
that no one can see your account balance.
The person who needs to check his account balance will only be able to
access private members via methods defined inside that class, and this method
will demand your account holder's name and password for authentication.
As a result, we can achieve security by using the principle of data hiding. This is
known as encapsulation.

Abstraction:
Abstraction means avoiding unnecessary and irrelevant information and only
showing the specific details of what users want to see. Or in other words,
abstraction refers to showing only the most relevant information while hiding the
details.
Example:
Every time you log into your email account (Gmail, Yahoo, Hotmail, or official
mail), many processes occur in the backend. You do not have any control over
how the password is verified, which keeps it safe from misuse.

Polymorphism:

Polymorphism means taking more than one form. Suppose you are in a
classroom at that time. You behave like a student. When you are in the market at
that time, you behave like a customer. When you are at your home at that time,
you behave like a son or daughter. In this case, one person is exhibiting a variety
of behaviors.
we use Operator overloading and Function overloading to achieve
polymorphism.
Operator Overloading: The process of making an operator exhibit different
behaviors in different instances is known as Operator overloading.
Function Overloading: When a single function name is used to execute many
tasks, this is known as function overloading.

Inheritance:

When one class inherits the capabilities from another class or when one object
acquires all the properties and behaviors of its parent object, then it is known
as Inheritance. It helps to reduce the code size.
A real-life example of inheritance is a child and parents. All the properties of the
father are inherited by his son.

What are the benefits and disadvantages of OOP and what are the applicationsof
OOP?
Principles or Advantages

1. Through inheritance, we can eliminate redundant code and extend the use
of existing class.
2. We can build a program from standing working modules that can
communicate with one another rather than having to start writing the code from
scratch. This leads to saving of development time and highs productivity.
3. The principles of data hiding helps programmer to build a secure
program. This codeis not overrun other parts of programs.
4. It is possible to have multiple objects to co exists without an interference.
5. It is easy to partition the work in a project based on objects.
6. The data-centered design approach to capture more details of model in an
implementation form.
7. Object oriented systems can be easily upgraded from small to large systems.
8. Message passing techniques for communication between objects make the
interface descriptions, with external systems much simpler.
9. Software complexity can be easily managed.

Applications of OOP

The most popular application Of OOP has been in the area of user interface design
such as windows. OOP is useful in this type of applications because it can simplify
complex problem. The promising areas for application of OOP include:

 Real time Systems.


 Simulation and modeling.
 Object oriented databases.
 Hypertext, hypermedia and expert text.
 Artificial Intelligence (AI) and expert systems.
 Neural networks and parallel programming.
 Decision support and office automation systems.
 CIM / CAD / CAM systems.
Some disadvantages:

 Steep learning curve: The thought process involved in oop’s may not be
natural for some people and it can take to get used to it. It is a programming
techniques such as inheritance and polymorphism can be challenging to a
comprehend initially
 Lager program size
 Slower programs
 Not suitable for all types of problems

7.Access Modifiers in Java:


In Java, Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member. It provides security, accessibility, etc to the user depending
upon the access modifier used with the element.

There are four types of access modifiers available in Java:


1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member – It is said to
be having the default access modifier by default. The data members, classes, or
methods that are not declared using any access modifiers i.e. having default access
modifiers are accessible only within the same package.

2. Private Access Modifier

The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they are
declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces can not be declared as private because
 private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any
subclasses”

3. Protected Access Modifier

The protected access modifier is specified using the keyword protected.


The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.

4. Public Access modifier

The public access modifier is specified using the keyword public.


 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data
members.
Access within within outside package outside
Modifier class package by subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

8.Constructors:
A constructor is similar to a method that is used to initialize the instance
variables of the objects of a class. The only purpose of a constructor is to
initialize the instance variables. A constructor has the following
characteristics.
1.Constructor name and class name must be same.
2. Constructor does not return any value. They do not specify a return type,
even we should not write void also.
3. A constructor may or may not have parameters. Parameters are variables to receive data
from outside into the

constructor. If a constructor does not have any parameters, it is called default


constructor.

4. If a constructor has one or more parameters, it is called parameterized constructor.

5. Constructor is automatically called & executed at the time of creating an object


6. A constructor is called and executed only once for each object.

Types of Constructors in Java

1. Default Constructor in Java


A constructor that has no parameters is known as default the 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.

import java.io.*;
class GFG
{
GFG()
{
System.out.println("Default constructor");
}
public static void main(String[] args)
{
GFG ob = new GFG();
}
}

Output: Default constructor

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized constructor. If we want
to initialize fields of the class with our own values, then use a parameterized
constructor.
Example:

import java.io.*;
class student
{
String name;
int id;
student(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG {
public static void main(String[] args)
{
student ob = new student("avinash", 68);
System.out.println("studentName :" + ob.name
+ " and studentId :" + ob.id);
}
}

9.Inheritance in Java
Java, 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. In Java, Inheritance means creating new classes based on
existing ones. A class that inherits from another class can reuse the methods and fields
of that class. In addition, you can add new fields and methods to your current class as
well.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

How to Use Inheritance in Java?


The extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to
increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Java Inheritance Types

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1. Single Inheritance

In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.

class Animal

void eat( )

System.out.println("eating...");

class Dog extends Animal

void bark( )

{
System.out.println("barking...");

class TestInheritance

public static void main(String args[ ])

Dog d=new Dog();

d.bark();

d.eat();

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as
well as the derived class also acts as the base class for other classes. In the below
image, class A serves as a base class for the derived class B, which in turn serves
as a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.

import java.io.*;

import java.lang.*;

import java.util.*;
class one

public void print_geek()

System.out.println("Geeks");

class two extends one

public void print_for()

System.out.println("for");

class three extends two

public void print_geek()

System.out.println("Geeks");

}
public class Main {

public static void main(String[] args)

three g = new three();

g.print_geek();

g.print_for();

g.print_geek();

3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the
derived classes B, C, and D.

class A

public void print_A()

System.out.println("Class A");

}
}

class B extends A

public void print_B()

System.out.println("Class B");

class C extends A

public void print_C()

System.out.println("Class C"); }

class D extends A

public void print_D()

System.out.println("Class D");

}
public class Test {

public static void main(String[] args)

B obj_B = new B();

obj_B.print_A();

obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();

obj_D.print_A();

obj_D.print_D();

4. Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.
5. Hybrid Inheritance(Through Interfaces)

It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance is also not possible with classes.
In Java, we can achieve hybrid inheritance only through Interfaces.

10.Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1. Use of super with Variables

This scenario occurs when a derived class and base class has the same data members. In
that case, there is a possibility of ambiguity for the JVM.
class Vehicle

int maxSpeed = 120;

class Car extends Vehicle


{

int maxSpeed = 180;

void display()

System.out.println("Maximum Speed: "+ super.maxSpeed);

class Test

public static void main(String[] args)

Car small = new Car();

small.display();

2. Use of super with Methods

This is used when we want to call the parent class method. So whenever a parent and
child class have the same-named methods then to resolve ambiguity we use the super
keyword.

class Person

void message()

{
System.out.println("This is person class\n");

class Student extends Person

void message()

System.out.println("This is student class");

void display()

message();

super.message();

class Test

public static void main(String args[])

Student s = new Student();

s.display();

3. Use of super with constructors


The super keyword can also be used to access the parent class constructor. One more
important thing is that ‘super’ can call both parametric as well as non-parametric
constructors depending on the situation.
class Person

Person()

System.out.println("Person class Constructor");

class Student extends Person

Student()

super();

System.out.println("Student class Constructor");

class Test

public static void main(String[] args)

Student s = new Student();

You might also like