Unit-I (Introduction to Java)

 JAVA

1. Java Defination:

Java is a programming language and a platform.

 Java is a simple, object oriented, distributed, robust, secure, architectural neutral, portable, interpreted, high performance, multithreaded and dynamic programming language.

 Platform: Any hardware or software environment in which a program runs is known as a platform.

Since Java has its own runtime environment (JRE) and API, it is called platform.

 

Java is used in the following applications:

1. Desktop Applications/ Standalone application/ window-based application 

An application that we need to install on every machine is called Desktop Application.

Ex: acrobat reader, media player, antivirus etc.

AWT and Swing are used in java for creating standalone applications.(J2SE)

2. Web Applications

An application that runs on the server side and creates dynamic page, is called web application.

Eg: irctc.co.in, cleartrip.com etc.

servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java

 

3. Enterprise Applications

An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security.

Eg: banking,e-commerce applications.

4. Mobile Applications (J2ME)

An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications

5. Embedded System

6. Smart Card

7. Robotics

8. Games etc.

Evolution of Java

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.

It is designed for electronic appliances like set-top boxes.

Firstly, it was called "Greentalk" by James Gosling and later “oak”

In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Java is an island of Indonesia where first coffee was produced

 JDK 1.0 released in(January 23, 1996).

Current stable release of Java is Java SE 8.

 

1. OOPs Concepts / OOPs Principles

Object means a real word entity such as pen, chair, table etc. 

Object-Oriented Programming is a methodology to design a program using classes and objects.

It improve code readability and reusability by defining java program efficiently.

It simplifies the software development and maintenance by providing some concepts:

Object

Class

Inheritance    - OOP Principle -2

Polymorphism - OOP Principle -3

Abstraction

Encapsulation - - OOP Principle -1

Object

Any entity that has state and behavior is known as an object.

Eg: chair, pen, table, keyboard, bike etc.

It can be physical and logical.

 

Class

Collection of objects that exhibit similar behavior is called class.

It is a logical entity.

 

Inheritance

When one object acquires all the properties and behaviors of parent object i.e. known as inheritance.

To use inheritance “extends” keyword is used.

It provides code reusability.

It is used to achieve runtime polymorphism.

Property transfer from Grand Parent to Parent – to children.

This is one way from top to bottom of hierarchy.

 

Polymorphism

When one task is performed by different ways i.e. known as polymorphism.

Ex: to convince the customer differently, to draw something e.g. shape or rectangle etc.

e.g. When we are in class – student ,

When we are in Market – Customer,

When we are in Home – Son / Daughter.

 

In java, we use method overloading and method overriding to achieve polymorphism.

 

Abstraction

Hiding internal details and showing functionality is known as abstraction.

ex: phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Shows important things to the user and hide the internals details.

e.g. ATM  , BIKE

 

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.

Date Hiding + Abstraction

ex:1)capsule, it is wrapped with different medicines,

2)Power Steering Car(Internally lot of Components tightly Coupled together)

 

A java class is the example of encapsulation.

Java bean is the fully encapsulated class because all the data members are private here.

 

 

 

 

 

 

 

 

 

2. Features of Java / Java Buzz Words

There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand.

1. Simple

2. Object-Oriented

3. Distributed

4. Robust

5. Secured

6. Platform independent

7. Portable

8. Architecture neutral

9. Interpreted

10. High Performance & Multithreaded

11. Dynamic

1. Simple:

Because its syntax is based on C, C++ (so easier for programmers to learn it after C++).

Also removed many confusing and rarely-used features e.g., explicit pointers, operator overloading etc.

2. Object-oriented

Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior.

And it follows all Oops features I.e.,

1. Object

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation

3. Distributed

We can create distributed applications which distributes Information on network.

RMI and EJB are used.

 

4. Robust

Java uses strong memory management.

There are lack of pointers that avoids security problem.

There is automatic garbage collection in java.

There is exception handling and type checking mechanism in java.

All these points makes java robust.

 

5. Secured

Because:

No explicit pointer

Java Programs run inside virtual machine sandbox

                                               


Classloader: adds security by separating the package for the classes of the local file system from those that are imported from network sources.

Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.

Security Manager: determines what resources a class can access such as reading and writing to the local disk.

 

6. Platform independent

Java code can be run on multiple platforms e.g. 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).

 

7. Portable

We may carry the java bytecode to any platform. It will gives same results.

8. Architecture neutral

There are no implementation dependent features e.g. size of primitive types is fixed.

9. Interpreted

Java compiles source code and generates binary byte-code.

This byte-code runs on the Java Virtual Machine (JVM), which is software-based interpreter.

The use of compiled byte-code allows the interpreter(JVM) to be small and efficient

10.  High Performance & Multithreaded

Java is faster than traditional interpretation since it contains Just-In-Time(JIT) Compiler along with Interpreter in JVM.

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.

Advantage: It doesn't occupy memory for each thread. It shares a common memory area.

Threads are important for multi-media, Web applications etc.

11.  Dynamic

 

Even we can develop the programs in java, which dynamically interact with user on Internet. Ex: Applets.

 

 

3. BASIC STRUCTURE OF A JAVA PROGRAM

 

public class Simple

{  

public static void main(String args[])

{  

System.out.println("Welcome To the World of Java");  

}  

}  

save this file as Simple.java

To compile:

javac Simple.java

To execute:

java Simple

 

class keyword is used to declare a class in java.

public keyword is an access modifier which represents visibility, it means it is visible to all.

static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.

void is the return type of the method, it means it doesn't return any value.

main represents startup of the program.

String[] args is used for command line argument.

System.out.println() is used print statement.

 

4. JVM Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java byte code can be executed.

JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.

  


 

1) Classloader: is used to load class files.

2) Class(Method) Area: The class code and the method code is stored.

3) Heap: It is the runtime data area in which objects are allocated.

4) Stack:

Java methods are executed in java stacks.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

It holds local variables and partial results, and plays a part in method invocation and return.

 

 

5) Program Counter Register

It contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack: It contains all the native methods used in the application.

7) Execution Engine


a)Interpreter: Read byte code stream then execute the instructions.

b)Just-In-Time (JIT) compiler: It is used to improve the performance. It reduces the amount of time needed for compilation.

Garbage Collector: Automatic freeing of Heap Memory.

 is an acronym for Java Runtime Environment.

— It is used to provide runtime environment.

—  It is the implementation of JVM.

— It physically exists.

— It contains set of libraries + other files that JVM uses at runtime.

— Implementation of JVMs is also actively released by other companies besides Sun Micro Systems.

JDK 

· JDK is an acronym for Java Development Kit.

· It physically exists. It contains JRE + development tools.


  

 

 

 

 

 

 

5. Java Variables

Variable is a name of memory location.

A Variable Has

1. NAME (VALID IDENTIFIER)

2. VALUE

3. TYPE

4. SCOPE & LIFETIME

Syntax: datatype  var_name = [initial value]

Ex: int data=50;

float p=3.142, result;

char grade =’A’;

 

Types of Variable: 3 types of variables in java:

 

1) Local Variable

A variable which is declared inside the method is called local variable. (Stored in Stack Area of Memory)

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable. This is not declared as static.(Stored in Heap area of Memory).

 

3) Static variable

A variable that is declared as static is called static variable. It cannot be local. It belongs to a class.(Stored in Class Area of Memory).

class A

{

int data=50;//instance variable-heap

static int m=100;//static variable-class area

 

void display()

{

int n=90;//local variable- stack area

 -----------

 -----------

}

}

 

6. Data Types in Java

It represents the type of data stored in variable and specify the different sizes.

 




Java is a strongly typed language.

 

 

Integer Data types: It represents integer numbers(without any decimal point).




 

Float Data types: It stores numbers with decimal point called floating point number.

1)float 4B -3.4e38 to +3.4e38

2)double 8B -1.7e308 to +1.7e308

Here ‘e’ means exponent -3.4*10^38

Java Character System:

Java Character set uses Unicode system.

Unicode is a universal international standard character encoding that is capable of representing most of the world's

 written languages.

There are no negative chars.

Java is designed to allow programs to be written for worldwide use, it makes sense that it would use Unicode to represent characters.

 

 

 

 

7. Type Casting/type conversion

Converting one primitive datatype into another is known as type casting (type conversion) in Java.

We can cast the primitive datatypes in two ways namely, Widening and, Narrowing.

Widening − Converting a lower datatype to a higher datatype is known as widening.

In this case the casting/conversion is done automatically therefore, it is known as implicit type casting.

In this case both datatypes should be compatible with each other.


 

public class WideningExample {

   public static void main(String args[]){

      char ch = 'C';

      int i = ch;

      System.out.println(i);

   }

}

Output: 67

Narrowing − Converting a higher datatype to a lower datatype is known as narrowing.

Hence there is the loss of data. That’s why this type of conversion is not done automatically, we need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting.

In this case both datatypes need not be compatible with each other.



 

class Type2

{

public static void main(String args[])

 {

byte b;

int i = 257,n=67;

double d = 323.142;

b = (byte) i;  //intàbyte

System.out.println("i and b " + i + "->" + b);

i = (int) d;    //doubleàint

System.out.println("d and i " + d + "->" + i);

b = (byte) d;  //doubleàbyte

System.out.println("d and b " + d + "-> " + b);

char ch=(char)n;

System.out.println("Character val of int is: ”+ch); //intàchar

 

String s= String.valueOf(n);  //intàString

System.out.println("String val of int is: ”+s);

}

}

  

8. Operators in Java

1)Arithmetic Operators

+       Additive operator (also used

        for String concatenation)

-       Subtraction operator

*       Multiplication operator

/       Division operator

%       Remainder operator

 

public class OperatorDemo

  {  

        public static void main(String args[])

              {  

 int a=10,b=5;  

 System.out.println(a+b);//15

 System.out.println(a-b);//5

 System.out.println(a*b);//50

 System.out.println(a/b);//2

System.ot.println(a%3);//1

  double c=42.25;

 System.out.println(c%10);//2.25possiblein java

  }  

}  

 

2)Assignment Operator

=       Simple assignment operator

+= Addition assignment operator

-= Subtraction assignment operator

*= Multiplication assignment operator

/= Division assignment operator

%= Remainder assignment operator

 

public class OperatorExample

    {  

           public static void main(String args[])

             {  

                 int a=10;  

                 int b=20;  

                 a+=4;//a=a+4 (a=10+4)  

                 b-=4;//b=b-4 (b=20-4)  

                System.out.println(a);  

                System.out.println(b);  

           }

}  

3)Relational / Conditional Operators

==      Equal to

!=      Not equal to

>       Greater than

>=      Greater than or equal to

<       Less than

<=      Less than or equal to

int a = 4;

int b = 1;

boolean c = a < b;

System.out.println(“The C value is “ + c) //false

System.out.println(a==4) //True

System.out.println(a!=b) //False

System.out.println(a<=4) //True

 

4)Logical Operators

&&      Conditional-AND

||      Conditional-OR

?:      Ternary (shorthand for  if-then-else statement)

^ logical xor

! logical not

class OperDemo

    {  

        public static void main(String args[])

             {  

                  int a=10;  

                  int b=5;   

                  int c=20;  

System.out.println(a<b&&a<c);

              //false && true = false                 

              System.out.println(a<b&a<c);

             //false & true = false  

 

                System.out.println(a>b  ||a<c);

                 //true || true = true  

System.out.println( a>b ^ a<c);

//Both are same result is  - False

 System.out.println( a<b ^ a>c);

// Both are same result is  - False

System.out.println( a>b ^ a>c);

// Both are different result is  - True

 System.out.println( a<b ^ a<c);

// Both are Different result is  - True

boolean c=true;  

                   System.out.println(!c);//false 

int a=20 , b=30;

       int c= (a>b) ? a : b;

System.out.println("The big is " + c);

 

        }

}  

 

5)Bitwise and Bit Shift Operators

~       Unary bitwise complement

<<      Signed left shift

>>      Signed right shift

>>>     Unsigned right shift

&       Bitwise AND

^       Bitwise exclusive OR

|       Bitwise inclusive OR

 

public class Operator

    {  

          public static void main(String args[])

               {  

byte  a=10;  

byte b=-10;  

                   System.out.println(~a); //-11 (one’s Complement)

                   System.out.println(~b);//9 (one’s Complement)

byte  a=10;  

byte b=8;  

byte c;  

                   c = a | b;

System.out.println(c);

                   c = a & b;

System.out.println(c);

c = a ^ b;

System.out.println(c);

 

//For positive number, >> and >>> works same  

    System.out.println(20>>2);  

    System.out.println(20>>>2);  

 

//For nagative number, >>> changes MSB to 0     

    System.out.println(-20>>2);

    System.out.println(-20>>>2);  

 

               }

      }  

 

6)Unary Operators

+       Unary plus operator; indicates  positive value (numbers are positive without this, however)

-       Unary minus operator; negates an expression

++      Increment operator; increments a value by 1

--      Decrement operator; decrements  a value by 1

!       Logical complement operator;      inverts the value of a boolean

public class OperatorDemo

  {  

public static void main(String args[])

           {  

int x=10;  

                 System.out.println(x++);//10 (11)

                 System.out.println(++x);//12

                 System.out.println(x--);//12 (11)  

                 System.out.println(--x);//10  

int a=10, b=10;  

               System.out.println(a++ + ++a);//10+12=22  

               System.out.println(a); //12

           }

}  

7)Type Comparison Operator

instanceof      Compares an object to

                a specified type

Operator Precedence Table in Java

 

Operator

       Category

                       Precedence

Unary

Postfix

expr++         expr--

Prefix

++expr          --expr    +expr  -expr   ~   !

Arithmetic

multiplicative

*   /  %

Additive

+   -

Shift

Shift

<<>>>>>

Relational

comparison

<><=    >=    instanceof

Equality

==    !=

Bitwise

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

Logical

logical AND

&&

logical OR

||

Ternary

Ternary

? :

Assignment

assignment

=   +=   -=    *=    /=    %=    &=    ^=  |=    <<=    >>=    >>>=

 

  public class OperatorExample

            {  

              public static void main(String args[])

                 {  

                      System.out.println(10*10/5+3-1*4/2);  //21

                    }

}  

 

9. Control Statements

 1. Conditional / Selection Statements

 

Java If-else Statement

The Java if statement is used to test the condition. It checks Boolean condition: true or false. There are various types of selection statement in java.

if statement (one way-selection)

if(condition)

   {  

       //code to be executed  

   }  

if-else statement (two way-selection)

if(condition)

   {  

       //code to be executed  

   }  

else

 {

       //code to be executed  

}

nested if statement ( if inside another if)

if(condition1)

   {  

if(condition2)

   {  

       //code to be executed  

   }  

 

//code to be executed  

   }  

if-else-if ladder          (Multi way  selection)

if(condition1)

   {  

       //code to be executed  

   }  

else if(condition2)

 {

       //code to be executed  

}

-----------------------

else

 {

       //code to be executed  

}

 

 

 

 

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.

switch(expression)

    {    

          case value1:  //code to be executed;    

                             break;  //optional  

          case value2:  //code to be executed;    

                             break;  //optional  

           ......    

          default:     

 // code to be executed if all cases are not matched;    

}    

public class WrapperInSwitchCaseExample {       

       public static void main(String args[])  

       {         

            Integer age = 18;        

            switch (age)  

            {  

                case (16):            

                    System.out.println("You are under 18.");  

                    break;  

                case (18):                

                    System.out.println("You are eligible for vote.");  

                    break;  

                case (65):                

                    System.out.println("You are senior citizen.");  

                    break;  

                default:  

                    System.out.println("Please give the valid age.");  

                    break;  

            }             

        }  }  

2. Loop / Repetitive / Iterative Statements

Java 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

Syntax:     while(condition)

    {  

        //code to be executed  

    }  

    while(true)   //infinite loop

       {  

           System.out.println("never ends");  

        }  

 

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

*** It is an event based loop, exit controlled loop

Syntax:do

{      //code to be executed  

}while(condition);  

Java for Loop

The Java for loop is used to iterate a part of the program several times.

If the number of iteration is fixed, it is recommended to use for loop.

*** It is a counter controlled loop, entry controlled loop

There are 2 types of for loop in java.

Simple For Loop

for-each or Enhanced For Loop

1. Java Simple 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:    for(int i=1;i<=10;i++)

 {  

            System.out.println(i);  

         } 

 

2. Java for-each Loop

The for-each loop is used to traverse array or collection in java.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

for(type var:array)

        {  

           //code to be executed  

          }  

 

int list[] = { 11, 2, 3, 14, 5, 62, 7, 8, 9, 10 };

int sum = 0;

for(int x :list)

        {

 System.out.println("Value is: " + x);

             sum = sum + x;

          }

Java Infinitive for Loop

   for(;;)

{  

        System.out.println("Never Ends");  

      }

 

3. Jump Statements

 

Java break Statement

§ The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified condition.

§ When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the nextstatement following the loop.

§ In case of inner loop, it breaks only inner loop.

    for(int i=1;i<=10;i++)

        {  

               if(i==5)

                 {  

                       break;  

                  }  

          }

        System.out.println(i);  

       

Java Continue Statement

§ The Java continue statement is used to continue loop.

§ We might want tocontinue running the loop but stop processing the remainder of the code in its body forthis particular iteration.

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

 

 

 

 

   for(int i=1;i<=6;i++)

       {  

            if(i==3)

{  

            continue;  

        }  

        System.out.println(i);  

    }  

 

Java return Statement

 

§ The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.

§ At any time in a method the return statement can be used to cause execution to branch back to the caller of the method.

§ Thus, the return statement immediately terminates the method in which it is executed.

 

public class Demo

{

public static void main(String[] args)

{

int res;

res = add(20,30);

System.out.println("The result is "+res);

}

public static int add(int a , int b)

  {

      return(a+b);

  }

}

1. Programs to Demonstrate Control Statements

[Hands on Session]

[Read Data From input Source]

1. Program to find net salary of an employee considering basic pay as <=20000 and above.

2. Program to find the grade of a student using switch.

3. Program to find the sum of the digits of a number.

4. Program to display a number in name.

[123 -> one two three]

5. Program to find factorial of a number using do-while.

6. Program to check a number is perfect number or not.

7. Program to display a list of fruits in an array using for-each loop.

8. Program to demonstrate use of break statement.

[Eg: Prime number or not.]

9. Program to demonstrate use of continue statement.

[Eg: the numbers divisible by 3 from 1 to 30.]

 

 

 

10. Arrays

An array is a group of like-typed(homogeneous) variables that are referred to by a common name.

A specific element in anarray is accessed by its index. (index starts from 0)

Arrays offer a convenient means of grouping related information.

The memory for an array is dynamically allocated unlike C or C++.

 

One-Dimensional Arrays

A one-dimensional array is, essentially, a list of like-typed variables.

The general form of a one-dimensionalarray declaration is

type var-name[ ]; //declaration

int days[];

double avg[ ];

 

public class Array

{

public static void main(String args[])

{

int days[] = new int[7];

days[0] = 12;  //assigning a value at index

days[1] = 22;

days[2] = 92;

days[3] = 28;

days[4] = 32;

days[5] = 40;

days[6] = 39;

 

//Accessing  an array element

            System.out.println(“The fourth element is “+ days[3]);

 

//Updating an array element

            days[2]=days[2]+99;

//Accessing  an array

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

             {

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

             }

 

      }

}

 

Array Initialization

type  arr_name[size] = { List of elements separated by comma}

 

Eg: int days[7] = {7,9,5,12,45,23,10};

public class Average

 {

     public static void main(String args[])

        {

double a[] = {75.1, 76.2, 65.3, 77.4, 84.5};

double sum = 0;

int i;

for(i=0; i<5; i++)

sum = sum + a[i];

System.out.println("Average is " + sum / 5);

}

}

 

Multi-Dimensional Arrays

 

In Java, multidimensional arrays are actually arrays of arrays.

To declare a multidimensional array variable, specify each additional

index using another set of square brackets.

 

Eg: A two-dimensional array can be declared and allocated as

int twoD[][] = new int[4][5];

as

class TwoD

{

public static void main(String args[])

{

int a[][]= new int[4][5];

int i, j, k = 0;

for(i=0; i<4; i++)

for(j=0; j<5; j++)

{

a[i][j] = k;

k++;

}

 

for(i=0; i<4; i++)

{

for(j=0; j<5; j++)

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

System.out.println();

}

}

}

 

A multi dimensional array can be initialized as

int a[3][3] = {{1,2,3}, {3,4,5},{6,7,8}};

int a[3][] = {{1,2,3}, {3,4,5},{6,7,8}};

int a[4][] = {{1,2,3,4}, {3,4 },{6,7,8,9},{1,2}};//Jagged array

 

 

11. COMMAND LINE ARGUMENTS

· The java command-line argument is an argument passed at the time of running the java program to main method.

· 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

· All command line arguments are of type String.

Simple example of command-line argument in java

 

public class Demo

           {  

                  public static void main(String args[])

                     {  

   System.out.println("First argument is: "+args[0]);  

                     }  

           }  

 

compile by > javac Demo.java  

run by > java Demo Vardhaman

Output: First argument is: Vardhaman

 

Example of command-line argument that prints all the values

 

class Demo{  

public static void main(String args[])

{  

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

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

  }  

}  

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions.

Java reserved words which are also highlighted with different colors be it an IDE or editor in order to segregate the differences between flexible words and reserved words.

These words are therefore not allowed to use as variable names or objects. If we do we will get a compile-time error as shown below as follows:

Java Language Keywords

They are listed below in the table with the primary action associated with them.

 

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

 

*

 

not used

**

 

added in 1.2

***

 

added in 1.4

****

 

added in 5.0

 

S.No

Keyword

Usage

1.

abstract

Specifies that a class or method will be implemented later, in a subclass 

2.

assert

Assert describes a predicate placed in a java program to indicate that the developer thinks that the predicate is always true at that place.

3. 

boolean

A data type that can hold True and False values only 

4.

break

A control statement for breaking out of loops.

5.

byte

A data type that can hold 8-bit data values 

6.

case

Used in switch statements to mark blocks of text

7.

catch

Catches exceptions generated by try statements

8.

char 

A data type that can hold unsigned 16-bit Unicode characters

9.

class

Declares a new class

10.

continue

Sends control back outside a loop 

11.

default

Specifies the default block of code in a switch statement

12.

do

Starts a do-while loop

13.

double

A data type that can hold 64-bit floating-point numbers

14.

else

Indicates alternative branches in an if statement 

15.

enum

A Java keyword is used to declare an enumerated type. Enumerations extend the base class.

16.

extends

Indicates that a class is derived from another class or interface 

17.

final

Indicates that a variable holds a constant value or that a method will not be overridden

18.

finally

Indicates a block of code in a try-catch structure that will always be executed

19.

float

A data type that holds a 32-bit floating-point number 

20.

for

Used to start a for loop

21.

if

Tests a true/false expression and branches accordingly

22.

implements

Specifies that a class implements an interface 

23.

import 

References other classes

24.

instanceof

Indicates whether an object is an instance of a specific class or implements an interface 

25.

int

A data type that can hold a 32-bit signed integer 

26.

interface

Declares an interface

27.

long

A data type that holds a 64-bit integer

28.

native

Specifies that a method is implemented with native (platform-specific) code 

29.

new

Creates new objects 

30.

null

This indicates that a reference does not refer to anything 

31.

package

Declares a Java package

32.

private

An access specifier indicating that a method or variable may be accessed only in the class it’s declared in

33.

protected

An access specifier indicating that a method or variable may only be accessed in the class it’s declared in (or a subclass of the class it’s declared in or other classes in the same package)

34.

public

An access specifier used for classes, interfaces, methods, and variables indicating that an item is accessible throughout the application (or where the class that defines it is accessible)

35.

return

Sends control and possibly a return value back from a called method 

36.

short

A data type that can hold a 16-bit integer 

37

static

Indicates that a variable or method is a class method (rather than being limited to one particular object)

38.

strictfp

A Java keyword is used to restrict the precision and rounding of floating-point calculations to ensure portability.

39.

super

Refers to a class’s base class (used in a method or class constructor) 

40.

switch

A statement that executes code based on a test value 

41.

synchronized

Specifies critical sections or methods in multithreaded code

42.

this

Refers to the current object in a method or constructor 

43.

throw 

Creates an exception 

44.

throws

Indicates what exceptions may be thrown by a method 

45.

transient

Specifies that a variable is not part of an object’s persistent state

46.

try

Starts a block of code that will be tested for exceptions 

47.

void

Specifies that a method does not have a return value

48.

volatile

This indicates that a variable may change asynchronously

49.

while

Starts a while loop.

Java Naming Convention

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.

Advantage of Naming Conventions in Java

By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.

Naming Conventions of the Different Identifiers

The following table shows the popular conventions used for the different identifiers.

Identifiers Type

Naming Rules

Examples

Class

It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms.

Public class Employee
{//code snippet
}

Interface

It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.

interface Printable
{//code snippet
}

Method

It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed().

class Employee{
void draw(){
//code snippet
}
}

Variable

It should start with a lowercase letter such as id, name.
It should not start with $ (dollar), _ (underscore), even both are allowed.

class Employee
{ int id; // variable
}

Package

It should be a lowercase letter such as java, lang.
If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.

package com.javatpoint;
class Employee{
….}

Constant

It should be in uppercase letters such as PI.

class Employee{
static final int MIN_AGE = 18;
}

 

 

1. Classes, Objects and Methods

· The class is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object.

· The class forms the basis for object-oriented programming in Java.

· Any concept we implement in a Java program must be encapsulated within a class.

· Collection of objects that exhibit similar behavior is called class.

· A class is declared by use of the class keyword.

Syntax: modifier class  ClassName

{

modifier type instance-variable1;  

modifier type instance-variable2;    

-------------------

modifier type instance-variableN;

modifier type methodname1(parameter-list)

{      

// body of method

}    

modifiertype methodname2(parameter-list)

{      

// body of method    

}    

-------------------

modifiertype methodnameN(parameter-list)

                 {       

 // body of method

   }

 }

· A class defines a new data type; using it we can create objects.

· A class is a template for an object, and an object is an instance of a class.

· A class contains data and the code that operates on that data.

· The data or variables, defined within a class are called instance variables, because each instance of the class (that is, each object of the class) contains its own copy of these variables

· The code is contained within methods.

· The methods and variables defined within a class are called members of the class.

Example 1:

class Fibonacci{  

 static int n1=0,n2=1,n3=0;    

 static void printFibonacci(int count){    

    if(count>0){    

         n3 = n1 + n2;    

         n1 = n2;    

         n2 = n3;    

         System.out.print(" "+n3);   

         printFibonacci(count-1);    

     }    

 }    

 public static void main(String args[]){    

  int count=10;    

  System.out.print(n1+" "+n2);//printing 0 and 1    

  printFibonacci(count-2);//n-2 because 2 numbers are already printed   

 }  

Example-2

class Employee

         {  

             int id;  

             String name;  

             double salary;  

 

            void insert(int i, String n, double s) 

              {  

                  id=i;  

                  name=n;  

                  salary=s;  

               }  

    

         void display()

          {

             System.out.println(id+" "+name+" "+salary);

          }  

}  

public class TestEmployee 

    {  

              public static void main(String[] args) 

                {  

                      Employee e1=new Employee();  

                      e1.insert(101,"Varun",45000);  

                      e1.display();  

     }

                } 

 

Example3:

 class Box

   {
double width;   // instance variable –heap memory

double height;  

double depth;  

double volume() 

                {

       double x;   // local variable – stack memory

                   x= width * height * depth;

                   return x;

                  }

                void setDim(double w, double h, double d)

                   {    

                        width = w;    

                        height = h;

                         depth = d;

                   }

     }

 class BoxDemo

   {

                public static void main(String args[])

                     {    

                               Box b1= new Box();    //b1 – reference variable

                               b1.setDim(10, 20, 15);    

             double vol1 = b1.volume();            

                              System.out.println(“box1 Volume is “ +vol1);

}

}

 

 

2. Methods

 

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions.

 

Syntax:

type methodName(parameter-list)

 {

// body of method

}

 

-type specifies the type of data returned by the method.

-If the method does not return a value, its return type must be void.

-The name of the method is any valid identifier name.

-The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.

-If the method has no parameters, then the parameter list will be empty.

-Methods that have a return type return a value to the calling routine using

return value;

 

A method can be  ->

1. With No Parameters and No Return Value

void volume()

                {

double x;     

                   x= width * height * depth;

                   System.out.println(“The Volume is “ +x);

                  }

2. With Parameters and No Return Value

void volume(double len , double wid, double hgt)

                {

double x=len*wid*hgt;     

                   System.out.println(“The Volume is “ +x);

                  }

3. With Parameters and a Return Value

double volume(doublelen , double wid, double hgt)

                {

double x=len*wid*hgt;     

        return x;

                  }

4. With No Parameters and a Return Value

double volume()

                {

double x;     

                   x= width * height * depth;

                   return x;

                  }

Parameter Passing Techniques in Java

· Formal Parameter: A variable and its type as they appear in the prototype of the method.

Syntax:

method_name(datatype  var1_name,  datatype  var2_name, …… )

double volume(double len , double wid, double hgt) //Method Prototype

  {

double x=len*wid*hgt;     

        return x;

 }

· len, wid and hgt are formal parameters.

             

· Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the method call in the calling environment.
Syntax:

method_name(var1_name ,  var2_name , ……);

public class Demo

    {  

        public static void main(String[] args)

           {  

double x=3.5;

double x=4.5;

double x=5.5;

---------------------

double res = volume(x,y,z);//Method Call

 ---------------------

}

                 }

· x,y,z are actual parameters

1. Pass By Value: 

ü Changes made to formal parameter do not get transmitted back to the caller.

ü Any modifications to the formal parameter variable inside the called method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment.

ü Inefficiency in storage allocation

ü For objects and arrays, the copy semantics are costly.

 

//Parameter Passing Program - Call By Value

class Test

{

   public static void update(int x, int y)

    {

        x++;

        y++;

System.out.println("x,yvalues are" +x  + " , " +y);//11,21

    }

}

public class ByVal

 {

    public static void main(String[] args)

    {

        int a = 10;

        int b = 20;

        Test t = new Test();

  System.out.println("The values of a, b before method call");   

  System.out.println("a, b values are" + a + "," + b); //10,20

t.update(a, b); //11,21

  System.out.println("The values of a, b after method call");

  System.out.println("a, b values are" + a + "," + b); //10,20

   }

}

 

 

2. Call by reference(aliasing): 

ü Changes made to formal parameter do get transmitted back to the caller through parameter passing.

ü Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference to the actual data.

ü This method is efficient in both time and space.

ü When we pass a reference, a new reference variable to the same object is created. So we can only change members of the object whose reference is passed. We cannot change the reference to refer to some other object as the received reference is a copy of the original reference. 

class Demo

 {

    int a, b;

    void update(Demo obj)

    {

obj.a += 10;

obj.b += 20;

    }

}

                   public class ByRef

 {

   public static void main(String[] args)

    {

          Demo d = new Demo();

          d.a = 10;

          d.b = 20;

System.out.println("a, b before method call");   

System.out.println( d.a + "," + d.b); //10,20

d.update(d);  // Method Call

System.out.println("a, b after method call");

System.out.println("a, b values are" + d.a + "," + d.b); //20,40

      }

}


3. Method Overloading

Polymorphism in Java is a concept by which we can perform a single action in different ways. i.e Poly means “many” and morphs means “forms”.

The two type of Polymorphism

1. Compile Time polymorphism

2. Run Time Polymorphism

***Compile Time polymorphism in Java is achieved using “method overloading”.

Defining two or more methods within the same class that share the same name but parameter declarations are different.The methods are said to be overloaded and the process is referred as method overloading.

· Overloaded methods must differ in type and/or number of parameters.

· When an overloaded method is called, Java simply executes the version of the method whose parameters match the arguments used in the call.

Advantage of method overloading

1. Method overloading increases the readability of the program.

2. Provides Compile time Polymorphism

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Method Overloading: By changing number of arguments

 

class Adder

{  

         int add(int a,int b)

 

{

return a+b;

}  

         int add(int a,int b,int c)

{

return a+b+c;

}  

     }  

 

public class Test

{  

        public static void main(String[] args)

{  

      Adder a = new Adder();

              System.out.println(a.add(10,11));//2-args Version

    System.out.println(a.add(10,11,12));//3-args Version

            }

     }  

***When a overloaded method is called, Java executes the version of the method whose parameters match the arguments used in the call.

 

2) Method Overloading: changing data type of arguments

 

class Adder

   {  

  int add(int a, int b)

            {

return a+b;

             }  

double add(double a, double b)

            {

return a+b;

             }  

    }  

 

public class Test

       {  

            public static void main(String[] args)

               {  

        Adder a = new Adder();

                  System.out.println(a.add(11,11));  //int version

                  System.out.println(a.add(12.3,12.6));  //double version

              }

       }  

Method Overloading is not possible by changing the return type of method only”

 

 “We can overload java main () method”

Yes, by method overloading. We can have any number of main methods in a class by method overloading. But JVM calls main () method which receives string array as arguments only.

          class Test

               {  

                  public static void main(String[] args)

                    {

                         System.out.println("main with String Array");

                      }  

public static void main(String args)

                       {

                            System.out.println("main with String");

                         }  

public static void main()

                     {

                        System.out.println("main without args");

                     }  

          }  

Output:   

main with String Array

  

 

Method Overloading and Type Promotion

One type is promoted to another implicitly if no matching data type is found. (Widening Process).




Ø As displayed in the above diagram, byte can be promoted to short, int, long, float or double.

Ø The short datatype can be promoted to int,long,float or double.

Ø The char datatype can be promoted to int,long,float or double and so on.

 

Example of Method Overloading with Type Promotion

 

   class Overloading

          {  

              void sum(int a,long b)

                 {

                      System.out.println(a+b);

                   }  

             void sum(int a,int b,int c)

                  {

                      System.out.println(a+b+c);

                  }  

  

           public static void main(String args[])

              {  

Overloading obj=new Overloading();

int a=20,b=20;

obj.sum(a,b);//40

//now second int literal will be promoted to long  

  obj.sum(20,20,20);  //60

               }  

    }  

***Example of Method Overloading with Type Promotion if matching found**

Ø If there are matching type arguments in the method, type promotion is not performed.

 

  class Overloading

             {  

                   void sum(int a,int b)

                       {

System.out.println(“int version” +(a+b));

                         }  

                    void sum(long a,long b)

                       {

System.out.println("long version"+(a+b));

                        }  

  

  public static void main(String args[])

        {  

   Overloading obj=new Overloading (); 

  obj.sum(20,20);// int version executed 

                     long x=345, y=678;

obj.sum(x,y);// long version executed 

   }  

}  

Example of Method Overloading with Type Promotion in case of ambiguity

Ø If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.

    class Overloading

            {  

                    void sum(int a,long b)

                       {

System.out.println(a+b);

                        }  

                   void sum(long a,int b)

                         {

  System.out.println(a+b);

                          }  

     public static void main(String args[])

           {  

   Overloading obj=new Overloading ();  

             obj.sum(20,20);//now ambiguity  

            }  

}  

Output:Compile Time Error

 

 

4. Constructors

 

§ Constructor in java is a special type of method that is used to initialize the object.

 

§ Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object hence it is known as constructor.

 

Characteristics

Ø Once defined, constructor is automatically called after the object is created, before the new operator completes.

Ø The name of the constructor must be same as its class name.

Ø Syntactically similar to a method

Ø By default constructor returns the object after constructing it.

Ø If no constructor is defined, a default constructor is invoked by Java.

Ø Constructor must not have explicit return type. By default a constructor returns the class instance after creation.

 

Types of java constructors

 

There are two types of constructors:

1. Default constructor (No-Argument  constructor)

ü Default constructor provides the default values to the object like 0(int), 0.0(double), null (String) etc. depending on the type.

ü The Constructor has no arguments.

ü Initializes all objects to same, hence no longer used.

 

Box()

 {

    Len = wid= hgt =0.0;

 }

 

Eg: Box b1 = new Box();

       Box b2 = new Box();

 

2. Parameterized constructor

ü A constructor that has parameters is known as parameterized constructor.

ü Used to create objects of different state and type.

ü Parameterized constructor is used to provide different values to the distinct objects.

Box(double x)

 {

    len = wid= hgt =x;

 }

 

Box(double x ,double y , double z)

{

len = x;

wid = y;

hgt = z;

}

Copy  constructor

ü There is no copy constructor specific in java. But, we can copy the values of one object to another.

ü Copy one object into another  

By constructor

By assigning the values of one object into another

// Example for Parameterized constructor-1

 

 

//By constructor

public class Student

 {  

    int id;  

    String name;  

    Student(int i,String n)

       {  

             id = i;  

             name = n;  

        }  

 

   Student(Student s)

        {  

              id = s.id;  

              name =s.name;  

        }  

 

    void display()

         {

              System.out.println(id+" "+name);

          }  

   

    

public static void main(String args[])

          {  

    Student s1 = new Student(1001, “Varun);  

    Student s2 = new Student(s1);  

               s1.display();  

               s2.display();  

            }  

}  

//Copying values without constructor

Ø We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

Example  Cnstructor default, parameterized, copy cnstructor

public class Student

   {  

            int id;  

            String name;  

    Student(int i,String n)

              {  

                   id = i;  

                   name = n;  

               }  

    Student( )

              {

               }  

       void display()

     {

   System.out.println(id+" "+name);

    }  

   public static void main(String args[])

           {  

    Student s1 = new Student(121,"Tarun");  

              Student s2 = new Student();  

              s2.id=s1.id;  

              s2.name=s1.name;  

     s1.display();  

     s2.display();  

   }  

}  

Difference between constructor and method in java

Java Constructor

Java Method

Constructor is used to initialize the state of an object.

Method is used to expose behavior of an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if we don't have any constructor.

Method is not provided by compiler in any case.

Constructor name must be same as the class name.

Method name is not same as class name

 

 Does constructor return any value?

 Yes, that is current class instance. (We cannot use return type explicitly,it returns an object by constructing it).

 

 Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, opening a file, calling method etc. We can perform any operation in the constructor like we perform in the method.

Ex: Box()

       {

          System.out.println(“It is a Default Constructor”);

          int x = 22;

x=x-2;

          System.out.println(“The is  “ +x);

         }

 

 

 

 

5. Overloading Constructors

§ Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter lists.

§ The compiler differentiates these constructors by taking into account the number of parameters in the list and their data type.

§ Like methods, the constructors in java can also be overloaded. This process is called constructor overloading.

 

//Example of Constructor Overloading  along with this keyword

 

class Student

{

 int rollno;    

String name, dept;

double avg;

 Student(){ }

 Student(int x)

{

     rollno = x;

}

 Student(int x , String y)

{

  this(x);

  name=y;

}

Student(int x , String y , double z )

{

  this(x,y);

  avg=z;

 }

Student(int x , String y , double z , String p )

{

  this(x,y,z);

  dept=p;

}

public void display()

{

     System.out.println("The Student Data is");

System.out.println(rollno + " , " +name +"," +avg + " ," +dept );

}

 

}

//StudentDemo.java

class StudentDemo

{

 public static void main(String args[])

{

Student s1 = new Student(510, "Dhanu" );

s1.avg = 87.5;

 s1.dept = "CSE";

 s1.display();

Student s2 = new Student(511, "Anjali" , 88.5 , "ECE");

s2.display();

}

}

 

6. this keyword

In java, this is a reference variable that refers to the current object.

Usage of  this keyword

1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.

         

1) this: to refer current class instance variable

 

When a local variable has the same name as an instance variable, the local variable hides the instance variable. This is called instance variable hiding.(Naming Collision).

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

2) this: to invoke current class method

We may invoke the method of the current class by using this keyword. If we don't use the keyword, compiler automatically adds this keyword while invoking the method.

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

//example  of this to invoke current class variable, method, cnstructor

class Student

   {  

               int rollno;  

               String name,course;  

               float fee;  

Student(int rollno,String name,String course)

                 {  

this.rollno=rollno;  

this.name=name;  

this.course=course;  

                 }  

Student(int rollno,String name,String course,float fee)

         {  

             this(rollno,name,course);//reusing constructor  

            this.fee=fee;  

         }  

       void display()

          {

  System.out.println(rollno+" "+name+" "+course+" "+fee);

          }  

}  

 

public class Test

    {  

          public static void main(String args[])

             {  

                Student s1=new Student(111,"ankit","java");  

                Student s2=new Student(112,"sumit","java",6000f);  

                s1.display();  

                s2.display();  

            }

    }  

 

Call to this( ) constructor  must be the first statement inside a constructor.

 

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:

      class S2

          {  

              void m(S2 obj)

                 {  

                     System.out.println("method is invoked");  

                  }  

              void p()

                  {  

                     m(this);  

                  }  

public static void main(String args[])

                  {  

                     S2 s1 = new S2();  

                     s1.p();  

                   }  

         }  

Output:

method is invoked

 

 

 

 


7. static keyword

 

Ø The keyword static is used in java for a variable, a block or a method.

Ø The static keyword belongs to a class but not to an object.

1. Java static variables.

§ Static keyword is used to define a class member that will be used independently of any object of that class.

§ A variable declared as static, then it is called static variable.

§ Instance variables declared as static are global variables.

§ A static variable can be used to refer to common property of all objects.

Eg: Company Name, College Name etc.

§ The static variables gets memory only once in a class area at the time of class is loading in to memory.

§ Static variables make the program memory efficient.  i.e. it saves memory.

§ A static variable can be accessed using class name without instantiating it.

Eg: Student.collegename

2. Java static block

Ø A block of code in a class, used to initialize the static data member.

Ø The static block is executed before main() method at the time of class is loading.

Ø A class can have any number of static blocks, executes them in the order they defined.

Ø A static block can access only static data.

 

3. Java static method

If we apply static keyword with any method, it is static method.

The restrictions of static on methods declared is

§ They can only directly call other static methods.

§ They can only directly access static data.

§ They cannot refer to with “this” or “super” keys in any way. Because the methods belongs to a class but not to objects.

Cannot access non static data variables, data or methods directly.

A static method is used to initialize or modify the static data.

A static method can be accessed without creating an instance of a class (object) directly using ClassName.

           Eg: ClassName.methodName();

 

Why Java main() method is static?

Java main method is static because

i) An object is not required to call static method.

ii) If it is non static method, JVM creates object first then call main( ) this leads to problem of extra memory allocation.

 

//static variable, blck, method

public class StaticDemo3

        {  

                   int a=40;//non static

 static int b=20; //static variable

static int c;

static     {

c=0;

c=c+12;

System.out.println("Static block 1 - " +c);

                            }

 

    static {

c=c-5;

System.out.println("Static block 2 - " +c);

      }

   public void show()

      {

  System.out.println("Non static method");

 }

         public static void display() //static method

{

                               b = b+5;   

                               System.out.println("Static Method");

 System.out.println(b);

}

}

                  public static void main(String args[])

                      {  

System.out.println(a);  

                            b=b+45;

                            System.out.println(b);  

display();

                       }  

           }        

 

 

 

 

 

 

 

 

 

 

 

 

1. String Class

 

Ø String is a sequence of characters.

Ø But in Java, string is an object that represents a sequence of characters.

Ø The java.lang.String class is used to create a string object.

Ø Java String class provides methods to perform operations on string 

 

Ø A String object is created using

By String Literal

 

Java String literal is created by using double quotes.

String s="welcome";  

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. 

 

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

String s1="Welcome";  

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

 

 

 

 

 

String class supports several constructors to create strings.

By new keyword.

 

1. String s = new String( );

 //default constructor – empty string

 

2. String s=new String("Welcome");

 

3. String(char chars[ ]);  

// parameterized constructor  - char array to string object

char ch[] = { 'w', 'e', 'l',’c’,’o’,’m’,’e’ };

String s1  = new String(ch); //”welcome”

 

4. String(char chars[ ], int startIndex, int numChars)

// parameterized constructor – char array to string object

                        char chars[] = { 'w', 'e', 'l',’c’,’o’,’m’,’e’ };

String  s2  = new String(chars, 3,4); //”come”

 

5. String(byte asciiChars[ ])

String(byte asciiChars[ ], int startIndex, int numChars)

 

byte ascii[] = {65, 66, 67, 68, 69, 70 };

                                   String s1 = new String(ascii);  //ABCDEF

System.out.println(s1);//”ABCDEF”

String s2= new String(ascii , 2,3); //”CDE”

 

6. String(String  strObj) // copy constructor

String  s1 = new String(“Hyderabad”);

      String s3 = new String(s1);

 

 

 

Ø The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created.

Ø Immutable simply means unmodifiable or unchangeable.

Ø Once string object is created its data or state can't be changed but a new string object is created with changes.

 

class String1

 {  

 public static void main(String args[])

  {  

    String s="Sachin";  

    s.concat(" Tendulkar");  

    System.out.println(s); // Sachin 

  }  

}  

 

 

 

Ø Here Sachin is not changed but a new object is created with Sachin Tendulkar. That is why string is known as immutable.

Ø As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".

Ø But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.

 

class String1

 {  

  public static void main(String args[])

   {  

     String s="Sachin";  

     s= s.concat(" Tendulkar");  

     System.out.println(s);// SachinTendulkar

  }  

}  

 

Reason: Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "sachin". If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

 

Ø For mutable strings, we can use StringBuffer and StringBuilder classes are used.

 

The methods of String Class are

Method Name

Description

Example

int   length()

returns string length

 

public int length() 

1. String s1="java";  

1. System.out.println("string length is: "+s1.length()); //4

2. 

3. System.out.println("string length is: "+”java”.length()); //4

char charAt(int index)

Extracts a single character from the string.

Returns char value for the particular index.

1. public char charAt(int index)  

 

 

1. String str="welcome";  

2. char ch=str.charAt(3); //c

 

String     substring(int beginIndex)

String     substring(int beginIndex, int endIndex)

 

Used to extract a substring from specified index from the main string.

Returns a substring.

String   s1="welcome"

String  str1= s1.substring(3); //come

String   str2 = s1.substring(3,5);

 //com

String   toLowerCase()

Returns a string in lowercase.

1. public String toLowerCase()  

 

1. String    s1="OBJECT oreinTED";  

2. String    str=s1.toLowerCase();  

3. System.out.println(str);  

4. //object oreinted

 

String  toUpperCase()

Returns a string in uppercase.

1. public String toUpperCase()  

 

5. String    s1="OBJECT oreinTED";  

6. String    str=s1.toUpperCase();  

7. System.out.println(str);  

8. //OBJECT  ORIENTED

 

void  getChars (int start, int end, char target[] , int tarstart)

 

Used to extract more than one character at a time.

Char buf[ ] = new char[10];

String str=”Welcome to Hyderabad”;

str.getChars(3,6,buf,0) //come

 

byte[]  getBytes()

Stores the characters in an array of bytes.

Strng str = new String(“Welcome to India”);

byte  b[ ] = str.getBytes();

char[]   toCharArray()

Converts all the characters ofA String object into a character array.

Strng str = new String(“Welcome to India”);

char ch[] = str.toCharArray();

 

 

String Comparison

boolean equals( Objectstr)

 

 

 

 

 

 

boolean  equalsIgnoreCase(String str)

 

 

 

 

boolean  startsWith()

 

 

 

 

boolean  endsWith()

 

 

 

 

 

 

 

equals()  versus   ==

 

 

 

 

 

 

 

 

 

 

int compareTo(String str )

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

int compareToIgnoreCase(String str )

 

 

 

 

 

Returns true if the strings contain same characters in same order otherwise returns false.

 

 

Compares two strings for equality and ignores the case differences.

 

 

Returns true, if the given string begins with a specified string.

 

 

 

Returns true, if the given string ends with a specified string.

 

 

 

equals() -> Compares the characters inside  a string object.

 

==  ->Compares two object references to see whether they refer to same instance.

 

 

 

 

Used to compare to strings.

It  returns

< 0:  The invoking string is less than the given string.

>0: The invoking string is

greater than the given string.

   0:  if the two strings are equal.

 

 

Same result as compareTo().

But ignores the case differences.

String   s1=”hello”;

String   s2=”hello”;

String   s3=”HELLO”;

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

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

//false

 

boolean x=s1.equalsIgnoreCase(s3));

//true

 

 

System.out.println(“welcome”.startsWith(“wel”)); //true

String str = new String(“Welcome”);

System.out.println(str.startsWith(“come”)); //false

 

System.out.println(“welcome”.endsWith(“wel”)); //false

 

String str = new String(“Welcome”);

System.out.println(str.endsWith(“come”)); //true

 

 

String s1 = new  “welcome”;

String  s2 = new String(s1);

String  s3= s1;

 

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

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

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

 

 

 

 

 

 

 

 

 

 

 

 

 

String s1 =”welcome”;

String s2= “hello”;

String s3 = “welcome”;

System.out.println(s1.compareTo(s3));    //0

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

System.out.println(s2.compareTo(s3));  // <0

 

 

 

String s1 =”welcome”;

String s3 = “WELcome”;

int x=s1.compareToIgnoreCase(s3));

//0

 

 

Searching Strings

 

int indexOf(int ch)

int indexOf(String str)

int indexOf(int ch , int start)

int indexOf(String str , int start)

int lastIndexOf(int ch)

int lastIndexOf(String str)

 

 

Used to search a string for a specified character or substring.

Returns index at which the character or string is found ,

Otherwise returns -1.

String str = “to do welcome to indian railways to come and well do of the rail works”

 

int x = str.indexOf(‘w’);

int x = str.indexOf(“wel”);

int x = str.indexOf(‘w’ , 10);

int x = str.lastIndexOf(‘r’);

 

 

 

 

Modifying  Strings

String substring(int start)

 

 

 

 

String substring(int start , int end)

 

 

String concat(String str)

 

 

 

String  replace(char old , char new)

 

 

 

 

 

 

String  trim()

 

 

 

 

 

+

To create a new copy of modified string the functions are used.

 

 

Returns a substring from specified index.

 

The two strings are concatenated.

 

 

Replaces all occurrences of one character in the invoking string with another character.

 

Returns a copy of invoking string from which any leading and trailing white space has been removed.

 

String concatenation

 

String   s1="welcome"

String   str1= s1.substring(3); //come

 

 

 

String   str2 = s1.substring(3,5);

 //com

 

 

String   s1 = “Welcome”;

String s2 = s1.concat(“To India”);

 

 

String   s1 = “Welcome”;

String s2 = s1.replace(‘e’ , ‘o’);

 

 

 

 

 

String   s1 = “  Welcome    ”;

String s2 = s1.trim(); //”welcome”

 

 

 

 

 

 

// String Concatenation

int  year=2019;

         String s2 = s1 +  "  " + year;

         System.out.println(s2);

         System.out.println(s2+2+2);

         System.out.println(s2+(2+2));

 

String toString()

Returns a String that contains the human readable form, which describes an object of a class.

String str=”Welcome to Hyd”;

String s = str.toString();

 

Box b1 = new Box();

String str = b1.toString();

 

 

boolean isEmpty()

Returns true if the string object is empty.

String s=””;

boolean x = s.isEmpty(); //true

String[] split(String  exp)

Returns a split string matching regular expression.

String str=”Welcome to Hyd for biryani”;

String  s[] = str.split(“\\s”);

Or

String  s[] = str.split(“ ”);

 

//splits string with white spaces.

 

 

 

 

//Converting String to particular type

public class  Demo

{

public static void main(String[] args)

{

String str1= "27";

//convert string to int

int x = Integer.parseInt(str1);

String str2= "345.67";

 //convert string to double

double d = Double.parseDouble(str2);

String str3="34.56";

 //convert string to float

 float f = Float.parseFloat(str3);

  String str4="4555526522426";

//convert string to long

  long y= Long.parseLong(str4);

 double res=  (d*y+x) / f;

  System.out.println("The result is " +res);

}

}

//String Operations

 

import java.io.*;

 

public class  StringOp1

{

public static void main(String[] args)

{

    // String length

String s1 = "Welcome to Java String Methods";

System.out.println("The no of characters are " + s1.length());

// String Concatenation

  int year = 2019;

  String s2 = s1 +  "  " + year;

 System.out.println(s2);

  System.out.println(s2+2+2);

   System.out.println(s2+(2+2));

 

 String str1= new String("Welcome");

 String s = str1.concat(" to India");

 System.out.println(s);

// Character Extraction

//String s1 = "Welcome to Java String Methods";

 

char ch1 = s1.charAt(3);

 System.out.println(ch1);

 

 char ch2[] = new char[5];

 s1.getChars(5,10,ch2,0);

 System.out.println(ch2);

 

 char ch3[ ] = new char[s1.length()];

 ch3 = s1.toCharArray();

 System.out.println(ch3);

 

          // String Comparisons

  String s3 = new String("WELCOME");

  String s4 = "WELCOME";

  String s5 = "welcome";

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

  System.out.println(s3.equals(s5));  //false

  System.out.println(s3.equalsIgnoreCase(s5)); //true

String s6 = s3;

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

  System.out.println(s3==s6); //true

 

  String s7 = "Food Time";

  System.out.println(s7.startsWith("Food")); //true

System.out.println(s7.endsWith("Time")); //true

System.out.println(s3.compareTo(s5));//-ve value

  //Searching Strings

 

System.out.println("The first occurance of l  is " + s1.indexOf('l'));

 System.out.println("The last occurance of l  is " + s1.lastIndexOf('l'));

 

System.out.println("The first occurance of l  is from 5 " + s1.indexOf('l',5));

  System.out.println("The last occurance of l  is from 5 " + s1.lastIndexOf('l',5));

System.out.println("The first occurance of me  is from 5 " + s1.indexOf("me",7))

 

System.out.println("The last occurance of me  is from 5 " + s1.lastIndexOf("me",7));

  //Modifying a string

  String str11 =  s1.substring(5);

String str22 = s1.substring(5, 15);

  System.out.println(str11);

System.out.println(str22);

 String str3 = s1.concat("Strings");

 System.out.println(str3);

String str4 =s1.replace("Java" , "Advanced Java");

System.out.println(str4);

 

String str5 = "      Welcome        ";

System.out.println(str5);

 System.out.println(str5.trim());

 

System.out.println(str5.toLowerCase());

System.out.println(str5.toUpperCase());  

 String s11 ="";

System.out.println(s11.isEmpty());

  String s22 = "welcome to India with love";

  String ss[ ]  = s22.split(" ");

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

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

}

}

//Program to use split() (Even Words list)

import java.util.*;

public class Task

{

public static void main(String args[])

{

Scanner sc = new Scanner(System.in);

System.out.println("Enter a line of Text");

String line = sc.nextLine();

String s[]= line.split(" ");

int count=0;

//for each loop

for(String word : s)

{

int len = word.length();

if(len % 2 == 0)

{

count++;

System.out.println(word + "    : " + len + "   : " +count);

}

}

}

}

 

 

 

 

StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

 

Constructors of StringBuffer Class

Constructor

Description

StringBuffer()

It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str)

It creates a String buffer with the specified string..

StringBuffer(int capacity)

It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class

Modifier and Type

Method

Description

public synchronized StringBuffer

append(String s)

It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

public synchronized StringBuffer

insert(int offset, String s)

It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.

public synchronized StringBuffer

replace(int startIndex, int endIndex, String str)

It is used to replace the string from specified startIndex and endIndex.

public synchronized StringBuffer

delete(int startIndex, int endIndex)

It is used to delete the string from specified startIndex and endIndex.

public synchronized StringBuffer

reverse()

is used to reverse the string.

public int

capacity()

It is used to return the current capacity.

public void

ensureCapacity(int minimumCapacity)

It is used to ensure the capacity at least equal to the given minimum.

public char

charAt(int index)

It is used to return the character at the specified position.

public int

length()

It is used to return the length of the string i.e. total number of characters.

public String

substring(int beginIndex)

It is used to return the substring from the specified beginIndex.

public String

substring(int beginIndex, int endIndex)

It is used to return the substring from the specified beginIndex and endIndex.

 

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("She sells sea shells ");

System.out.println("Given stringbuffer is: " + sb);

System.out.println("length of stringbuffer is: " + sb.length() + ", capacity of stringbuffer is: " + sb.capacity());

System.out.println("character at index 5 of the stringbuffer is: " + sb.charAt(5));

System.out.println("appendind the stringbuffer: " + sb.append("on the sea shore"));

System.out.println("substring of stringbuffer from index 10 to 20 is: " + sb.substring(10,20));

System.out.println("reverse of the stringbuffer is: " + sb.reverse());

}

}

 

String reverse example:

import java.util.Scanner;

 

public class StringReverse{

public static void main(String[] args){

Scanner in=new Scanner(System.in);

System.out.println("Enter the string to reverse: ");

    String str=in.nextLine();

StringBuffer sb= new StringBuffer(str);

    String reverse =sb.reverse().toString();

    System.out.println("String after reverse:"+reverse);

}

}

 

 

 

 

super 

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

 

class Animal{  

Animal(){System.out.println("animal is created");} 

String color="white";  

void eat(){System.out.println("Animal eating...");}  

}  

class Dog extends Animal{  

String color="black"

Dog(){  

super();  

System.out.println("dog is created");  

}  

 

void eat(){System.out.println("dog eating...");}  

void printColor(){  

System.out.println(color);//prints color of Dog class  

System.out.println(super.color);//prints color of Animal class  

super.eat();  

}  

}  

class TestSuper1{  

public static void main(String args[]){  

Dog d=new Dog();  

d.printColor();

d.eat();  

}} 

 

 

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a String into tokens.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens.

 

 

 

There are 3 constructors defined in the StringTokenizer class.

Constructor

Description

StringTokenizer(String str)

It creates StringTokenizer with specified string.

StringTokenizer(String str, String delim)

It creates StringTokenizer with specified string and delimiter.

StringTokenizer(String str, String delim, boolean returnValue)

It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class

Methods

Description

boolean hasMoreTokens()

It checks if there is more tokens available.

String nextToken()

It returns the next token from the StringTokenizer object.

String nextToken(String delim)

It returns the next token based on the delimiter.

boolean hasMoreElements()

It is the same as hasMoreTokens() method.

Object nextElement()

It is the same as nextToken() but its return type is Object.

int countTokens()

It returns the total number of tokens.

Example of StringTokenizer Class

import java.util.StringTokenizer;  

public class Simple{  

 public static void main(String args[]){  

   StringTokenizer st = new StringTokenizer("my name is khan"," ");  

     while (st.hasMoreTokens()) {  

         System.out.println(st.nextToken());  

     }  

   }  

}  

 

 

 

Eg:

import java.util.StringTokenizer;    

public class StringTokenizer1  

{    

 /* Driver Code */  

 public static void main(String args[])  

 {    

   /* StringTokenizer object */  

   StrJAVA

1. Java Defination:

Java is a programming language and a platform.

 Java is a simple, object oriented, distributed, robust, secure, architectural neutral, portable, interpreted, high performance, multithreaded and dynamic programming language.

 Platform: Any hardware or software environment in which a program runs is known as a platform.

Since Java has its own runtime environment (JRE) and API, it is called platform.

 

Java is used in the following applications:

1. Desktop Applications/ Standalone application/ window-based application 

An application that we need to install on every machine is called Desktop Application.

Ex: acrobat reader, media player, antivirus etc.

AWT and Swing are used in java for creating standalone applications.(J2SE)

2. Web Applications

An application that runs on the server side and creates dynamic page, is called web application.

Eg: irctc.co.in, cleartrip.com etc.

servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java

 

3. Enterprise Applications

An application that is distributed in nature, such as banking applications etc. It has the advantage of high level security.

Eg: banking,e-commerce applications.

4. Mobile Applications (J2ME)

An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile applications

5. Embedded System

6. Smart Card

7. Robotics

8. Games etc.

Evolution of Java

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.

It is designed for electronic appliances like set-top boxes.

Firstly, it was called "Greentalk" by James Gosling and later “oak”

In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Java is an island of Indonesia where first coffee was produced

 JDK 1.0 released in(January 23, 1996).

Current stable release of Java is Java SE 8.

 

1. OOPs Concepts / OOPs Principles

Object means a real word entity such as pen, chair, table etc. 

Object-Oriented Programming is a methodology to design a program using classes and objects.

It improve code readability and reusability by defining java program efficiently.

It simplifies the software development and maintenance by providing some concepts:

Object

Class

Inheritance    - OOP Principle -2

Polymorphism - OOP Principle -3

Abstraction

Encapsulation - - OOP Principle -1

Object

Any entity that has state and behavior is known as an object.

Eg: chair, pen, table, keyboard, bike etc.

It can be physical and logical.

 

Class

Collection of objects that exhibit similar behavior is called class.

It is a logical entity.

 

Inheritance

When one object acquires all the properties and behaviors of parent object i.e. known as inheritance.

To use inheritance “extends” keyword is used.

It provides code reusability.

It is used to achieve runtime polymorphism.

Property transfer from Grand Parent to Parent – to children.

This is one way from top to bottom of hierarchy.

 

Polymorphism

When one task is performed by different ways i.e. known as polymorphism.

Ex: to convince the customer differently, to draw something e.g. shape or rectangle etc.

e.g. When we are in class – student ,

When we are in Market – Customer,

When we are in Home – Son / Daughter.

 

In java, we use method overloading and method overriding to achieve polymorphism.

 

Abstraction

Hiding internal details and showing functionality is known as abstraction.

ex: phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

Shows important things to the user and hide the internals details.

e.g. ATM  , BIKE

 

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation.

Date Hiding + Abstraction

ex:1)capsule, it is wrapped with different medicines,

2)Power Steering Car(Internally lot of Components tightly Coupled together)

 

A java class is the example of encapsulation.

Java bean is the fully encapsulated class because all the data members are private here.

 

 

 

 

 

 

 

 

 

2. Features of Java / Java Buzz Words

There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand.

1. Simple

2. Object-Oriented

3. Distributed

4. Robust

5. Secured

6. Platform independent

7. Portable

8. Architecture neutral

9. Interpreted

10. High Performance & Multithreaded

11. Dynamic

1. Simple:

Because its syntax is based on C, C++ (so easier for programmers to learn it after C++).

Also removed many confusing and rarely-used features e.g., explicit pointers, operator overloading etc.

2. Object-oriented

Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior.

And it follows all Oops features I.e.,

1. Object

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation

3. Distributed

We can create distributed applications which distributes Information on network.

RMI and EJB are used.

 

4. Robust

Java uses strong memory management.

There are lack of pointers that avoids security problem.

There is automatic garbage collection in java.

There is exception handling and type checking mechanism in java.

All these points makes java robust.

 

5. Secured

Because:

No explicit pointer

Java Programs run inside virtual machine sandbox

                                               

Classloader: adds security by separating the package for the classes of the local file system from those that are imported from network sources.

Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.

Security Manager: determines what resources a class can access such as reading and writing to the local disk.

 

6. Platform independent

Java code can be run on multiple platforms e.g. 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).

 

7. Portable

We may carry the java bytecode to any platform. It will gives same results.

8. Architecture neutral

There are no implementation dependent features e.g. size of primitive types is fixed.

9. Interpreted

Java compiles source code and generates binary byte-code.

This byte-code runs on the Java Virtual Machine (JVM), which is software-based interpreter.

The use of compiled byte-code allows the interpreter(JVM) to be small and efficient

10.  High Performance & Multithreaded

Java is faster than traditional interpretation since it contains Just-In-Time(JIT) Compiler along with Interpreter in JVM.

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.

Advantage: It doesn't occupy memory for each thread. It shares a common memory area.

Threads are important for multi-media, Web applications etc.

11.  Dynamic

 

Even we can develop the programs in java, which dynamically interact with user on Internet. Ex: Applets.

 

 

3. BASIC STRUCTURE OF A JAVA PROGRAM

 

public class Simple

{  

public static void main(String args[])

{  

System.out.println("Welcome To the World of Java");  

}  

}  

save this file as Simple.java

To compile:

javac Simple.java

To execute:

java Simple

 

class keyword is used to declare a class in java.

public keyword is an access modifier which represents visibility, it means it is visible to all.

static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.

void is the return type of the method, it means it doesn't return any value.

main represents startup of the program.

String[] args is used for command line argument.

System.out.println() is used print statement.

 

4. JVM Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java byte code can be executed.

JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.

  

 

1) Classloader: is used to load class files.

2) Class(Method) Area: The class code and the method code is stored.

3) Heap: It is the runtime data area in which objects are allocated.

4) Stack:

Java methods are executed in java stacks.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

It holds local variables and partial results, and plays a part in method invocation and return.

 

 

5) Program Counter Register

It contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack: It contains all the native methods used in the application.

7) Execution Engine

 

 

a)Interpreter: Read byte code stream then execute the instructions.

b)Just-In-Time (JIT) compiler: It is used to improve the performance. It reduces the amount of time needed for compilation.

Garbage Collector: Automatic freeing of Heap Memory.

 

 

 

 

 

 

 

 

JRE

— JRE is an acronym for Java Runtime Environment.

— It is used to provide runtime environment.

—  It is the implementation of JVM.

— It physically exists.

— It contains set of libraries + other files that JVM uses at runtime.

— Implementation of JVMs is also actively released by other companies besides Sun Micro Systems.

JDK 

· JDK is an acronym for Java Development Kit.

· It physically exists. It contains JRE + development tools.

 

 

 

 

 

 

 

5. Java Variables

Variable is a name of memory location.

A Variable Has

1. NAME (VALID IDENTIFIER)

2. VALUE

3. TYPE

4. SCOPE & LIFETIME

Syntax: datatype  var_name = [initial value]

Ex: int data=50;

float p=3.142, result;

char grade =’A’;

 

Types of Variable: 3 types of variables in java:

 

 

1) Local Variable

A variable which is declared inside the method is called local variable. (Stored in Stack Area of Memory)

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance variable. This is not declared as static.(Stored in Heap area of Memory).

 

3) Static variable

A variable that is declared as static is called static variable. It cannot be local. It belongs to a class.(Stored in Class Area of Memory).

class A

{

int data=50;//instance variable-heap

static int m=100;//static variable-class area

 

void display()

{

int n=90;//local variable- stack area

 -----------

 -----------

}

}

 

6. Data Types in Java

It represents the type of data stored in variable and specify the different sizes.

 

Java is a strongly typed language.

 

 

Integer Data types: It represents integer numbers(without any decimal point).

 

Float Data types: It stores numbers with decimal point called floating point number.

1)float 4B -3.4e38 to +3.4e38

2)double 8B -1.7e308 to +1.7e308

Here ‘e’ means exponent -3.4*10^38

Java Character System:

Java Character set uses Unicode system.

Unicode is a universal international standard character encoding that is capable of representing most of the world's

 written languages.

There are no negative chars.

Java is designed to allow programs to be written for worldwide use, it makes sense that it would use Unicode to represent characters.

 

 

 

 

7. Type Casting/type conversion

Converting one primitive datatype into another is known as type casting (type conversion) in Java.

We can cast the primitive datatypes in two ways namely, Widening and, Narrowing.

Widening − Converting a lower datatype to a higher datatype is known as widening.

In this case the casting/conversion is done automatically therefore, it is known as implicit type casting.

In this case both datatypes should be compatible with each other.

 

public class WideningExample {

   public static void main(String args[]){

      char ch = 'C';

      int i = ch;

      System.out.println(i);

   }

}

Output: 67

Narrowing − Converting a higher datatype to a lower datatype is known as narrowing.

Hence there is the loss of data. That’s why this type of conversion is not done automatically, we need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting.

In this case both datatypes need not be compatible with each other.

 

class Type2

{

public static void main(String args[])

 {

byte b;

int i = 257,n=67;

double d = 323.142;

b = (byte) i;  //intàbyte

System.out.println("i and b " + i + "->" + b);

i = (int) d;    //doubleàint

System.out.println("d and i " + d + "->" + i);

b = (byte) d;  //doubleàbyte

System.out.println("d and b " + d + "-> " + b);

char ch=(char)n;

System.out.println("Character val of int is: ”+ch); //intàchar

 

String s= String.valueOf(n);  //intàString

System.out.println("String val of int is: ”+s);

}

}

 

 

 

 

 

 

 

8. Operators in Java

1)Arithmetic Operators

+       Additive operator (also used

        for String concatenation)

-       Subtraction operator

*       Multiplication operator

/       Division operator

%       Remainder operator

 

public class OperatorDemo

  {  

        public static void main(String args[])

              {  

 int a=10,b=5;  

 System.out.println(a+b);//15

 System.out.println(a-b);//5

 System.out.println(a*b);//50

 System.out.println(a/b);//2

System.ot.println(a%3);//1

  double c=42.25;

 System.out.println(c%10);//2.25possiblein java

  }  

}  

 

 

 

 

 

 

 

 

2)Assignment Operator

=       Simple assignment operator

+= Addition assignment operator

-= Subtraction assignment operator

*= Multiplication assignment operator

/= Division assignment operator

%= Remainder assignment operator

 

public class OperatorExample

    {  

           public static void main(String args[])

             {  

                 int a=10;  

                 int b=20;  

                 a+=4;//a=a+4 (a=10+4)  

                 b-=4;//b=b-4 (b=20-4)  

                System.out.println(a);  

                System.out.println(b);  

           }

}  

3)Relational / Conditional Operators

==      Equal to

!=      Not equal to

>       Greater than

>=      Greater than or equal to

<       Less than

<=      Less than or equal to

int a = 4;

int b = 1;

boolean c = a < b;

System.out.println(“The C value is “ + c) //false

System.out.println(a==4) //True

System.out.println(a!=b) //False

System.out.println(a<=4) //True

 

4)Logical Operators

&&      Conditional-AND

||      Conditional-OR

?:      Ternary (shorthand for  if-then-else statement)

^ logical xor

! logical not

class OperDemo

    {  

        public static void main(String args[])

             {  

                  int a=10;  

                  int b=5;   

                  int c=20;  

System.out.println(a<b&&a<c);

              //false && true = false                 

              System.out.println(a<b&a<c);

             //false & true = false  

 

                System.out.println(a>b  ||a<c);

                 //true || true = true  

System.out.println( a>b ^ a<c);

//Both are same result is  - False

 System.out.println( a<b ^ a>c);

// Both are same result is  - False

System.out.println( a>b ^ a>c);

// Both are different result is  - True

 System.out.println( a<b ^ a<c);

// Both are Different result is  - True

boolean c=true;  

                   System.out.println(!c);//false 

int a=20 , b=30;

       int c= (a>b) ? a : b;

System.out.println("The big is " + c);

 

        }

}  

 

5)Bitwise and Bit Shift Operators

~       Unary bitwise complement

<<      Signed left shift

>>      Signed right shift

>>>     Unsigned right shift

&       Bitwise AND

^       Bitwise exclusive OR

|       Bitwise inclusive OR

 

public class Operator

    {  

          public static void main(String args[])

               {  

byte  a=10;  

byte b=-10;  

                   System.out.println(~a); //-11 (one’s Complement)

                   System.out.println(~b);//9 (one’s Complement)

byte  a=10;  

byte b=8;  

byte c;  

                   c = a | b;

System.out.println(c);

                   c = a & b;

System.out.println(c);

c = a ^ b;

System.out.println(c);

 

//For positive number, >> and >>> works same  

    System.out.println(20>>2);  

    System.out.println(20>>>2);  

 

//For nagative number, >>> changes MSB to 0     

    System.out.println(-20>>2);

    System.out.println(-20>>>2);  

 

               }

      }  

 

6)Unary Operators

+       Unary plus operator; indicates  positive value (numbers are positive without this, however)

-       Unary minus operator; negates an expression

++      Increment operator; increments a value by 1

--      Decrement operator; decrements  a value by 1

!       Logical complement operator;      inverts the value of a boolean

public class OperatorDemo

  {  

public static void main(String args[])

           {  

int x=10;  

                 System.out.println(x++);//10 (11)

                 System.out.println(++x);//12

                 System.out.println(x--);//12 (11)  

                 System.out.println(--x);//10  

int a=10, b=10;  

               System.out.println(a++ + ++a);//10+12=22  

               System.out.println(a); //12

           }

}  

7)Type Comparison Operator

instanceof      Compares an object to

                a specified type

Operator Precedence Table in Java

 

Operator

       Category

                       Precedence

Unary

Postfix

expr++         expr--

Prefix

++expr          --expr    +expr  -expr   ~   !

Arithmetic

multiplicative

*   /  %

Additive

+   -

Shift

Shift

<<>>>>>

Relational

comparison

<><=    >=    instanceof

Equality

==    !=

Bitwise

bitwise AND

&

bitwise exclusive OR

^

bitwise inclusive OR

|

Logical

logical AND

&&

logical OR

||

Ternary

Ternary

? :

Assignment

assignment

=   +=   -=    *=    /=    %=    &=    ^=  |=    <<=    >>=    >>>=

 

  public class OperatorExample

            {  

              public static void main(String args[])

                 {  

                      System.out.println(10*10/5+3-1*4/2);  //21

                    }

}  

 

9. Control Statements

 

1. Conditional / Selection Statements

 

Java If-else Statement

The Java if statement is used to test the condition. It checks Boolean condition: true or false. There are various types of selection statement in java.

if statement (one way-selection)

if(condition)

   {  

       //code to be executed  

   }  

if-else statement (two way-selection)

if(condition)

   {  

       //code to be executed  

   }  

else

 {

       //code to be executed  

}

nested if statement ( if inside another if)

if(condition1)

   {  

if(condition2)

   {  

       //code to be executed  

   }  

 

//code to be executed  

   }  

if-else-if ladder          (Multi way  selection)

if(condition1)

   {  

       //code to be executed  

   }  

else if(condition2)

 {

       //code to be executed  

}

-----------------------

else

 {

       //code to be executed  

}

 

 

 

 

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.

switch(expression)

    {    

          case value1:  //code to be executed;    

                             break;  //optional  

          case value2:  //code to be executed;    

                             break;  //optional  

           ......    

          default:     

 // code to be executed if all cases are not matched;    

}    

public class WrapperInSwitchCaseExample {       

       public static void main(String args[])  

       {         

            Integer age = 18;        

            switch (age)  

            {  

                case (16):            

                    System.out.println("You are under 18.");  

                    break;  

                case (18):                

                    System.out.println("You are eligible for vote.");  

                    break;  

                case (65):                

                    System.out.println("You are senior citizen.");  

                    break;  

                default:  

                    System.out.println("Please give the valid age.");  

                    break;  

            }             

        }  }  

2. Loop / Repetitive / Iterative Statements

Java 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

Syntax:     while(condition)

    {  

        //code to be executed  

    }  

    while(true)   //infinite loop

       {  

           System.out.println("never ends");  

        }  

 

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

*** It is an event based loop, exit controlled loop

Syntax:do

{      //code to be executed  

}while(condition);  

Java for Loop

The Java for loop is used to iterate a part of the program several times.

If the number of iteration is fixed, it is recommended to use for loop.

*** It is a counter controlled loop, entry controlled loop

There are 2 types of for loop in java.

Simple For Loop

for-each or Enhanced For Loop

1. Java Simple 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:    for(int i=1;i<=10;i++)

 {  

            System.out.println(i);  

         } 

 

2. Java for-each Loop

The for-each loop is used to traverse array or collection in java.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

for(type var:array)

        {  

           //code to be executed  

          }  

 

int list[] = { 11, 2, 3, 14, 5, 62, 7, 8, 9, 10 };

int sum = 0;

for(int x :list)

        {

 System.out.println("Value is: " + x);

             sum = sum + x;

          }

Java Infinitive for Loop

   for(;;)

{  

        System.out.println("Never Ends");  

      }

 

 

 

 

 

 

 

 

 

 

 

3. Jump Statements

 

Java break Statement

§ The Java break is used to break loop or switch statement. It breaks the current flow of the program at specified condition.

§ When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the nextstatement following the loop.

§ In case of inner loop, it breaks only inner loop.

    for(int i=1;i<=10;i++)

        {  

               if(i==5)

                 {  

                       break;  

                  }  

          }

        System.out.println(i);  

       

Java Continue Statement

§ The Java continue statement is used to continue loop.

§ We might want tocontinue running the loop but stop processing the remainder of the code in its body forthis particular iteration.

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

 

 

 

 

   for(int i=1;i<=6;i++)

       {  

            if(i==3)

{  

            continue;  

        }  

        System.out.println(i);  

    }  

 

Java return Statement

 

§ The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.

§ At any time in a method the return statement can be used to cause execution to branch back to the caller of the method.

§ Thus, the return statement immediately terminates the method in which it is executed.

 

public class Demo

{

public static void main(String[] args)

{

int res;

res = add(20,30);

System.out.println("The result is "+res);

}

public static int add(int a , int b)

  {

      return(a+b);

  }

}

1. Programs to Demonstrate Control Statements

[Hands on Session]

[Read Data From input Source]

1. Program to find net salary of an employee considering basic pay as <=20000 and above.

2. Program to find the grade of a student using switch.

3. Program to find the sum of the digits of a number.

4. Program to display a number in name.

[123 -> one two three]

5. Program to find factorial of a number using do-while.

6. Program to check a number is perfect number or not.

7. Program to display a list of fruits in an array using for-each loop.

8. Program to demonstrate use of break statement.

[Eg: Prime number or not.]

9. Program to demonstrate use of continue statement.

[Eg: the numbers divisible by 3 from 1 to 30.]

 

 

 

 

 

 

 

 

 

 

10. Arrays

An array is a group of like-typed(homogeneous) variables that are referred to by a common name.

A specific element in anarray is accessed by its index. (index starts from 0)

Arrays offer a convenient means of grouping related information.

The memory for an array is dynamically allocated unlike C or C++.

 

One-Dimensional Arrays

A one-dimensional array is, essentially, a list of like-typed variables.

The general form of a one-dimensionalarray declaration is

type var-name[ ]; //declaration

int days[];

double avg[ ];

 

public class Array

{

public static void main(String args[])

{

int days[] = new int[7];

days[0] = 12;  //assigning a value at index

days[1] = 22;

days[2] = 92;

days[3] = 28;

days[4] = 32;

days[5] = 40;

days[6] = 39;

 

//Accessing  an array element

            System.out.println(“The fourth element is “+ days[3]);

 

//Updating an array element

            days[2]=days[2]+99;

//Accessing  an array

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

             {

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

             }

 

      }

}

 

Array Initialization

type  arr_name[size] = { List of elements separated by comma}

 

Eg: int days[7] = {7,9,5,12,45,23,10};

public class Average

 {

     public static void main(String args[])

        {

double a[] = {75.1, 76.2, 65.3, 77.4, 84.5};

double sum = 0;

int i;

for(i=0; i<5; i++)

sum = sum + a[i];

System.out.println("Average is " + sum / 5);

}

}

 

Multi-Dimensional Arrays

 

In Java, multidimensional arrays are actually arrays of arrays.

To declare a multidimensional array variable, specify each additional

index using another set of square brackets.

 

Eg: A two-dimensional array can be declared and allocated as

int twoD[][] = new int[4][5];

as

class TwoD

{

public static void main(String args[])

{

int a[][]= new int[4][5];

int i, j, k = 0;

for(i=0; i<4; i++)

for(j=0; j<5; j++)

{

a[i][j] = k;

k++;

}

 

for(i=0; i<4; i++)

{

for(j=0; j<5; j++)

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

System.out.println();

}

}

}

 

A multi dimensional array can be initialized as

int a[3][3] = {{1,2,3}, {3,4,5},{6,7,8}};

int a[3][] = {{1,2,3}, {3,4,5},{6,7,8}};

int a[4][] = {{1,2,3,4}, {3,4 },{6,7,8,9},{1,2}};//Jagged array

 

 

11. COMMAND LINE ARGUMENTS

· The java command-line argument is an argument passed at the time of running the java program to main method.

· 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

· All command line arguments are of type String.

Simple example of command-line argument in java

 

public class Demo

           {  

                  public static void main(String args[])

                     {  

   System.out.println("First argument is: "+args[0]);  

                     }  

           }  

 

compile by > javac Demo.java  

run by > java Demo Vardhaman

Output: First argument is: Vardhaman

 

Example of command-line argument that prints all the values

 

class Demo{  

public static void main(String args[])

{  

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

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

  }  

}  

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions.

Java reserved words which are also highlighted with different colors be it an IDE or editor in order to segregate the differences between flexible words and reserved words.

These words are therefore not allowed to use as variable names or objects. If we do we will get a compile-time error as shown below as follows:

Java Language Keywords

They are listed below in the table with the primary action associated with them.

 

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

 

*

 

not used

**

 

added in 1.2

***

 

added in 1.4

****

 

added in 5.0

 

S.No

Keyword

Usage

1.

abstract

Specifies that a class or method will be implemented later, in a subclass 

2.

assert

Assert describes a predicate placed in a java program to indicate that the developer thinks that the predicate is always true at that place.

3. 

boolean

A data type that can hold True and False values only 

4.

break

A control statement for breaking out of loops.

5.

byte

A data type that can hold 8-bit data values 

6.

case

Used in switch statements to mark blocks of text

7.

catch

Catches exceptions generated by try statements

8.

char 

A data type that can hold unsigned 16-bit Unicode characters

9.

class

Declares a new class

10.

continue

Sends control back outside a loop 

11.

default

Specifies the default block of code in a switch statement

12.

do

Starts a do-while loop

13.

double

A data type that can hold 64-bit floating-point numbers

14.

else

Indicates alternative branches in an if statement 

15.

enum

A Java keyword is used to declare an enumerated type. Enumerations extend the base class.

16.

extends

Indicates that a class is derived from another class or interface 

17.

final

Indicates that a variable holds a constant value or that a method will not be overridden

18.

finally

Indicates a block of code in a try-catch structure that will always be executed

19.

float

A data type that holds a 32-bit floating-point number 

20.

for

Used to start a for loop

21.

if

Tests a true/false expression and branches accordingly

22.

implements

Specifies that a class implements an interface 

23.

import 

References other classes

24.

instanceof

Indicates whether an object is an instance of a specific class or implements an interface 

25.

int

A data type that can hold a 32-bit signed integer 

26.

interface

Declares an interface

27.

long

A data type that holds a 64-bit integer

28.

native

Specifies that a method is implemented with native (platform-specific) code 

29.

new

Creates new objects 

30.

null

This indicates that a reference does not refer to anything 

31.

package

Declares a Java package

32.

private

An access specifier indicating that a method or variable may be accessed only in the class it’s declared in

33.

protected

An access specifier indicating that a method or variable may only be accessed in the class it’s declared in (or a subclass of the class it’s declared in or other classes in the same package)

34.

public

An access specifier used for classes, interfaces, methods, and variables indicating that an item is accessible throughout the application (or where the class that defines it is accessible)

35.

return

Sends control and possibly a return value back from a called method 

36.

short

A data type that can hold a 16-bit integer 

37

static

Indicates that a variable or method is a class method (rather than being limited to one particular object)

38.

strictfp

A Java keyword is used to restrict the precision and rounding of floating-point calculations to ensure portability.

39.

super

Refers to a class’s base class (used in a method or class constructor) 

40.

switch

A statement that executes code based on a test value 

41.

synchronized

Specifies critical sections or methods in multithreaded code

42.

this

Refers to the current object in a method or constructor 

43.

throw 

Creates an exception 

44.

throws

Indicates what exceptions may be thrown by a method 

45.

transient

Specifies that a variable is not part of an object’s persistent state

46.

try

Starts a block of code that will be tested for exceptions 

47.

void

Specifies that a method does not have a return value

48.

volatile

This indicates that a variable may change asynchronously

49.

while

Starts a while loop.

Java Naming Convention

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc.

But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.

All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code.

Advantage of Naming Conventions in Java

By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.

Naming Conventions of the Different Identifiers

The following table shows the popular conventions used for the different identifiers.

Identifiers Type

Naming Rules

Examples

Class

It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms.

Public class Employee
{
//code snippet
}

Interface

It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
Use appropriate words, instead of acronyms.

interface Printable
{
//code snippet
}

Method

It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed().

class Employee
{
// method
void draw()
{
//code snippet
}
}

Variable

It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
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.

class Employee
{
// variable
int id;
//code snippet
}

Package

It should be a lowercase letter such as java, lang.
If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.

//package
package com.javatpoint;
class Employee
{
//code snippet
}

Constant

It should be in uppercase letters such as RED, YELLOW.
If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY.
It may contain digits but not as the first letter.

class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1. Classes, Objects and Methods

· The class is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object.

· The class forms the basis for object-oriented programming in Java.

· Any concept we implement in a Java program must be encapsulated within a class.

· Collection of objects that exhibit similar behavior is called class.

· A class is declared by use of the class keyword.

Syntax: modifier class  ClassName

{

modifier type instance-variable1;  

modifier type instance-variable2;    

-------------------

modifier type instance-variableN;

modifier type methodname1(parameter-list)

{      

// body of method

}    

modifiertype methodname2(parameter-list)

{      

// body of method    

}    

-------------------

modifiertype methodnameN(parameter-list)

                 {       

 // body of method

   }

 }

· A class defines a new data type; using it we can create objects.

· A class is a template for an object, and an object is an instance of a class.

· A class contains data and the code that operates on that data.

· The data or variables, defined within a class are called instance variables, because each instance of the class (that is, each object of the class) contains its own copy of these variables

· The code is contained within methods.

· The methods and variables defined within a class are called members of the class.

Example 1:

class Fibonacci{  

 static int n1=0,n2=1,n3=0;    

 static void printFibonacci(int count){    

    if(count>0){    

         n3 = n1 + n2;    

         n1 = n2;    

         n2 = n3;    

         System.out.print(" "+n3);   

         printFibonacci(count-1);    

     }    

 }    

 public static void main(String args[]){    

  int count=10;    

  System.out.print(n1+" "+n2);//printing 0 and 1    

  printFibonacci(count-2);//n-2 because 2 numbers are already printed   

 }  

Example-2

class Employee

         {  

             int id;  

             String name;  

             double salary;  

 

            void insert(int i, String n, double s) 

              {  

                  id=i;  

                  name=n;  

                  salary=s;  

               }  

    

         void display()

          {

             System.out.println(id+" "+name+" "+salary);

          }  

}  

public class TestEmployee 

    {  

              public static void main(String[] args) 

                {  

                      Employee e1=new Employee();  

                      e1.insert(101,"Varun",45000);  

                      e1.display();  

     }

                } 

 

Example3:

 class Box

   {
double width;   // instance variable –heap memory

double height;  

double depth;  

double volume() 

                {

       double x;   // local variable – stack memory

                   x= width * height * depth;

                   return x;

                  }

                void setDim(double w, double h, double d)

                   {    

                        width = w;    

                        height = h;

                         depth = d;

                   }

     }

 class BoxDemo

   {

                public static void main(String args[])

                     {    

                               Box b1= new Box();    //b1 – reference variable

                               b1.setDim(10, 20, 15);    

             double vol1 = b1.volume();            

                              System.out.println(“box1 Volume is “ +vol1);

}

}

 

 

2. Methods

 

A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions.

 

Syntax:

type methodName(parameter-list)

 {

// body of method

}

 

-type specifies the type of data returned by the method.

-If the method does not return a value, its return type must be void.

-The name of the method is any valid identifier name.

-The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.

-If the method has no parameters, then the parameter list will be empty.

-Methods that have a return type return a value to the calling routine using

return value;

 

A method can be  ->

1. With No Parameters and No Return Value

void volume()

                {

double x;     

                   x= width * height * depth;

                   System.out.println(“The Volume is “ +x);

                  }

2. With Parameters and No Return Value

void volume(double len , double wid, double hgt)

                {

double x=len*wid*hgt;     

                   System.out.println(“The Volume is “ +x);

                  }

3. With Parameters and a Return Value

double volume(doublelen , double wid, double hgt)

                {

double x=len*wid*hgt;     

        return x;

                  }

4. With No Parameters and a Return Value

double volume()

                {

double x;     

                   x= width * height * depth;

                   return x;

                  }

Parameter Passing Techniques in Java

· Formal Parameter: A variable and its type as they appear in the prototype of the method.

Syntax:

method_name(datatype  var1_name,  datatype  var2_name, …… )

double volume(double len , double wid, double hgt) //Method Prototype

  {

double x=len*wid*hgt;     

        return x;

 }

· len, wid and hgt are formal parameters.

             

· Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the method call in the calling environment.
Syntax:

method_name(var1_name ,  var2_name , ……);

public class Demo

    {  

        public static void main(String[] args)

           {  

double x=3.5;

double x=4.5;

double x=5.5;

---------------------

double res = volume(x,y,z);//Method Call

 ---------------------

}

                 }

· x,y,z are actual parameters

1. Pass By Value: 

ü Changes made to formal parameter do not get transmitted back to the caller.

ü Any modifications to the formal parameter variable inside the called method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment.

ü Inefficiency in storage allocation

ü For objects and arrays, the copy semantics are costly.

 

//Parameter Passing Program - Call By Value

class Test

{

   public static void update(int x, int y)

    {

        x++;

        y++;

System.out.println("x,yvalues are" +x  + " , " +y);//11,21

    }

}

public class ByVal

 {

    public static void main(String[] args)

    {

        int a = 10;

        int b = 20;

        Test t = new Test();

  System.out.println("The values of a, b before method call");   

  System.out.println("a, b values are" + a + "," + b); //10,20

t.update(a, b); //11,21

  System.out.println("The values of a, b after method call");

  System.out.println("a, b values are" + a + "," + b); //10,20

   }

}

 

 

2. Call by reference(aliasing): 

ü Changes made to formal parameter do get transmitted back to the caller through parameter passing.

ü Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference to the actual data.

ü This method is efficient in both time and space.

ü When we pass a reference, a new reference variable to the same object is created. So we can only change members of the object whose reference is passed. We cannot change the reference to refer to some other object as the received reference is a copy of the original reference. 

class Demo

 {

    int a, b;

    void update(Demo obj)

    {

obj.a += 10;

obj.b += 20;

    }

}

                   public class ByRef

 {

   public static void main(String[] args)

    {

          Demo d = new Demo();

          d.a = 10;

          d.b = 20;

System.out.println("a, b before method call");   

System.out.println( d.a + "," + d.b); //10,20

d.update(d);  // Method Call

System.out.println("a, b after method call");

System.out.println("a, b values are" + d.a + "," + d.b); //20,40

      }

}


3. Method Overloading

Polymorphism in Java is a concept by which we can perform a single action in different ways. i.e Poly means “many” and morphs means “forms”.

The two type of Polymorphism

1. Compile Time polymorphism

2. Run Time Polymorphism

***Compile Time polymorphism in Java is achieved using “method overloading”.

Defining two or more methods within the same class that share the same name but parameter declarations are different.The methods are said to be overloaded and the process is referred as method overloading.

· Overloaded methods must differ in type and/or number of parameters.

· When an overloaded method is called, Java simply executes the version of the method whose parameters match the arguments used in the call.

Advantage of method overloading

1. Method overloading increases the readability of the program.

2. Provides Compile time Polymorphism

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Method Overloading: By changing number of arguments

 

class Adder

{  

         int add(int a,int b)

 

{

return a+b;

}  

         int add(int a,int b,int c)

{

return a+b+c;

}  

     }  

 

public class Test

{  

        public static void main(String[] args)

{  

      Adder a = new Adder();

              System.out.println(a.add(10,11));//2-args Version

    System.out.println(a.add(10,11,12));//3-args Version

            }

     }  

***When a overloaded method is called, Java executes the version of the method whose parameters match the arguments used in the call.

 

2) Method Overloading: changing data type of arguments

 

class Adder

   {  

  int add(int a, int b)

            {

return a+b;

             }  

double add(double a, double b)

            {

return a+b;

             }  

    }  

 

public class Test

       {  

            public static void main(String[] args)

               {  

        Adder a = new Adder();

                  System.out.println(a.add(11,11));  //int version

                  System.out.println(a.add(12.3,12.6));  //double version

              }

       }  

Method Overloading is not possible by changing the return type of method only”

 

 “We can overload java main () method”

Yes, by method overloading. We can have any number of main methods in a class by method overloading. But JVM calls main () method which receives string array as arguments only.

          class Test

               {  

                  public static void main(String[] args)

                    {

                         System.out.println("main with String Array");

                      }  

public static void main(String args)

                       {

                            System.out.println("main with String");

                         }  

public static void main()

                     {

                        System.out.println("main without args");

                     }  

          }  

Output:   

main with String Array

 

 

 

 

 

 

Method Overloading and Type Promotion

One type is promoted to another implicitly if no matching data type is found. (Widening Process).

 

Ø As displayed in the above diagram, byte can be promoted to short, int, long, float or double.

Ø The short datatype can be promoted to int,long,float or double.

Ø The char datatype can be promoted to int,long,float or double and so on.

 

Example of Method Overloading with Type Promotion

 

   class Overloading

          {  

              void sum(int a,long b)

                 {

                      System.out.println(a+b);

                   }  

             void sum(int a,int b,int c)

                  {

                      System.out.println(a+b+c);

                  }  

  

           public static void main(String args[])

              {  

Overloading obj=new Overloading();

int a=20,b=20;

obj.sum(a,b);//40

//now second int literal will be promoted to long  

  obj.sum(20,20,20);  //60

               }  

    }  

***Example of Method Overloading with Type Promotion if matching found**

Ø If there are matching type arguments in the method, type promotion is not performed.

 

  class Overloading

             {  

                   void sum(int a,int b)

                       {

System.out.println(“int version” +(a+b));

                         }  

                    void sum(long a,long b)

                       {

System.out.println("long version"+(a+b));

                        }  

  

  public static void main(String args[])

        {  

   Overloading obj=new Overloading (); 

  obj.sum(20,20);// int version executed 

                     long x=345, y=678;

obj.sum(x,y);// long version executed 

   }  

}  

Example of Method Overloading with Type Promotion in case of ambiguity

Ø If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.

    class Overloading

            {  

                    void sum(int a,long b)

                       {

System.out.println(a+b);

                        }  

                   void sum(long a,int b)

                         {

  System.out.println(a+b);

                          }  

     public static void main(String args[])

           {  

   Overloading obj=new Overloading ();  

             obj.sum(20,20);//now ambiguity  

            }  

}  

Output:Compile Time Error

 

 

4. Constructors

 

§ Constructor in java is a special type of method that is used to initialize the object.

 

§ Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object hence it is known as constructor.

 

Characteristics

Ø Once defined, constructor is automatically called after the object is created, before the new operator completes.

Ø The name of the constructor must be same as its class name.

Ø Syntactically similar to a method

Ø By default constructor returns the object after constructing it.

Ø If no constructor is defined, a default constructor is invoked by Java.

Ø Constructor must not have explicit return type. By default a constructor returns the class instance after creation.

 

Types of java constructors

 

There are two types of constructors:

1. Default constructor (No-Argument  constructor)

ü Default constructor provides the default values to the object like 0(int), 0.0(double), null (String) etc. depending on the type.

ü The Constructor has no arguments.

ü Initializes all objects to same, hence no longer used.

 

Box()

 {

    Len = wid= hgt =0.0;

 }

 

Eg: Box b1 = new Box();

       Box b2 = new Box();

 

2. Parameterized constructor

ü A constructor that has parameters is known as parameterized constructor.

ü Used to create objects of different state and type.

ü Parameterized constructor is used to provide different values to the distinct objects.

Box(double x)

 {

    len = wid= hgt =x;

 }

 

Box(double x ,double y , double z)

{

len = x;

wid = y;

hgt = z;

}

Copy  constructor

ü There is no copy constructor specific in java. But, we can copy the values of one object to another.

ü Copy one object into another  

By constructor

By assigning the values of one object into another

// Example for Parameterized constructor-1

 

 

//By constructor

public class Student

 {  

    int id;  

    String name;  

    Student(int i,String n)

       {  

             id = i;  

             name = n;  

        }  

 

   Student(Student s)

        {  

              id = s.id;  

              name =s.name;  

        }  

 

    void display()

         {

              System.out.println(id+" "+name);

          }  

   

    

public static void main(String args[])

          {  

    Student s1 = new Student(1001, “Varun);  

    Student s2 = new Student(s1);  

               s1.display();  

               s2.display();  

            }  

}  

//Copying values without constructor

Ø We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

Example  Cnstructor default, parameterized, copy cnstructor

public class Student

   {  

            int id;  

            String name;  

    Student(int i,String n)

              {  

                   id = i;  

                   name = n;  

               }  

    Student( )

              {

               }  

       void display()

     {

   System.out.println(id+" "+name);

    }  

   public static void main(String args[])

           {  

    Student s1 = new Student(121,"Tarun");  

              Student s2 = new Student();  

              s2.id=s1.id;  

              s2.name=s1.name;  

     s1.display();  

     s2.display();  

   }  

}  

Difference between constructor and method in java

Java Constructor

Java Method

Constructor is used to initialize the state of an object.

Method is used to expose behavior of an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if we don't have any constructor.

Method is not provided by compiler in any case.

Constructor name must be same as the class name.

Method name is not same as class name

 

 Does constructor return any value?

 Yes, that is current class instance. (We cannot use return type explicitly,it returns an object by constructing it).

 

 Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, opening a file, calling method etc. We can perform any operation in the constructor like we perform in the method.

Ex: Box()

       {

          System.out.println(“It is a Default Constructor”);

          int x = 22;

x=x-2;

          System.out.println(“The is  “ +x);

         }

 

 

 

 

5. Overloading Constructors

§ Constructor overloading is a technique in which a class can have any number of constructors that differ in parameter lists.

§ The compiler differentiates these constructors by taking into account the number of parameters in the list and their data type.

§ Like methods, the constructors in java can also be overloaded. This process is called constructor overloading.

 

//Example of Constructor Overloading  along with this keyword

 

class Student

{

 int rollno;    

String name, dept;

double avg;

 Student(){ }

 Student(int x)

{

     rollno = x;

}

 Student(int x , String y)

{

  this(x);

  name=y;

}

Student(int x , String y , double z )

{

  this(x,y);

  avg=z;

 }

Student(int x , String y , double z , String p )

{

  this(x,y,z);

  dept=p;

}

public void display()

{

     System.out.println("The Student Data is");

System.out.println(rollno + " , " +name +"," +avg + " ," +dept );

}

 

}

//StudentDemo.java

class StudentDemo

{

 public static void main(String args[])

{

Student s1 = new Student(510, "Dhanu" );

s1.avg = 87.5;

 s1.dept = "CSE";

 s1.display();

Student s2 = new Student(511, "Anjali" , 88.5 , "ECE");

s2.display();

}

}

 

6. this keyword

In java, this is a reference variable that refers to the current object.

Usage of  this keyword

1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.

         

1) this: to refer current class instance variable

 

When a local variable has the same name as an instance variable, the local variable hides the instance variable. This is called instance variable hiding.(Naming Collision).

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

2) this: to invoke current class method

We may invoke the method of the current class by using this keyword. If we don't use the keyword, compiler automatically adds this keyword while invoking the method.

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

//example  of this to invoke current class variable, method, cnstructor

class Student

   {  

               int rollno;  

               String name,course;  

               float fee;  

Student(int rollno,String name,String course)

                 {  

this.rollno=rollno;  

this.name=name;  

this.course=course;  

                 }  

Student(int rollno,String name,String course,float fee)

         {  

             this(rollno,name,course);//reusing constructor  

            this.fee=fee;  

         }  

       void display()

          {

  System.out.println(rollno+" "+name+" "+course+" "+fee);

          }  

}  

 

public class Test

    {  

          public static void main(String args[])

             {  

                Student s1=new Student(111,"ankit","java");  

                Student s2=new Student(112,"sumit","java",6000f);  

                s1.display();  

                s2.display();  

            }

    }  

 

Call to this( ) constructor  must be the first statement inside a constructor.

 

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:

      class S2

          {  

              void m(S2 obj)

                 {  

                     System.out.println("method is invoked");  

                  }  

              void p()

                  {  

                     m(this);  

                  }  

public static void main(String args[])

                  {  

                     S2 s1 = new S2();  

                     s1.p();  

                   }  

         }  

Output:

method is invoked

 

 

 

 


7. static keyword

 

Ø The keyword static is used in java for a variable, a block or a method.

Ø The static keyword belongs to a class but not to an object.

1. Java static variables.

§ Static keyword is used to define a class member that will be used independently of any object of that class.

§ A variable declared as static, then it is called static variable.

§ Instance variables declared as static are global variables.

§ A static variable can be used to refer to common property of all objects.

Eg: Company Name, College Name etc.

§ The static variables gets memory only once in a class area at the time of class is loading in to memory.

§ Static variables make the program memory efficient.  i.e. it saves memory.

§ A static variable can be accessed using class name without instantiating it.

Eg: Student.collegename

2. Java static block

Ø A block of code in a class, used to initialize the static data member.

Ø The static block is executed before main() method at the time of class is loading.

Ø A class can have any number of static blocks, executes them in the order they defined.

Ø A static block can access only static data.

 

3. Java static method

If we apply static keyword with any method, it is static method.

The restrictions of static on methods declared is

§ They can only directly call other static methods.

§ They can only directly access static data.

§ They cannot refer to with “this” or “super” keys in any way. Because the methods belongs to a class but not to objects.

Cannot access non static data variables, data or methods directly.

A static method is used to initialize or modify the static data.

A static method can be accessed without creating an instance of a class (object) directly using ClassName.

           Eg: ClassName.methodName();

 

Why Java main() method is static?

Java main method is static because

i) An object is not required to call static method.

ii) If it is non static method, JVM creates object first then call main( ) this leads to problem of extra memory allocation.

 

//static variable, blck, method

public class StaticDemo3

        {  

                   int a=40;//non static

 static int b=20; //static variable

static int c;

static     {

c=0;

c=c+12;

System.out.println("Static block 1 - " +c);

                            }

 

    static {

c=c-5;

System.out.println("Static block 2 - " +c);

      }

   public void show()

      {

  System.out.println("Non static method");

 }

         public static void display() //static method

{

                               b = b+5;   

                               System.out.println("Static Method");

 System.out.println(b);

}

}

                  public static void main(String args[])

                      {  

System.out.println(a);  

                            b=b+45;

                            System.out.println(b);  

display();

                       }  

           }        

 

 

 

 

 

 

 

 

 

 

 

 

1. String Class

 

Ø String is a sequence of characters.

Ø But in Java, string is an object that represents a sequence of characters.

Ø The java.lang.String class is used to create a string object.

Ø Java String class provides methods to perform operations on string 

 

Ø A String object is created using

By String Literal

 

Java String literal is created by using double quotes.

String s="welcome";  

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. 

 

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

String s1="Welcome";  

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

 

 

 

 

 

String class supports several constructors to create strings.

By new keyword.

 

1. String s = new String( );

 //default constructor – empty string

 

2. String s=new String("Welcome");

 

3. String(char chars[ ]);  

// parameterized constructor  - char array to string object

char ch[] = { 'w', 'e', 'l',’c’,’o’,’m’,’e’ };

String s1  = new String(ch); //”welcome”

 

4. String(char chars[ ], int startIndex, int numChars)

// parameterized constructor – char array to string object

                        char chars[] = { 'w', 'e', 'l',’c’,’o’,’m’,’e’ };

String  s2  = new String(chars, 3,4); //”come”

 

5. String(byte asciiChars[ ])

String(byte asciiChars[ ], int startIndex, int numChars)

 

byte ascii[] = {65, 66, 67, 68, 69, 70 };

                                   String s1 = new String(ascii);  //ABCDEF

System.out.println(s1);//”ABCDEF”

String s2= new String(ascii , 2,3); //”CDE”

 

6. String(String  strObj) // copy constructor

String  s1 = new String(“Hyderabad”);

      String s3 = new String(s1);

 

 

 

Ø The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created.

Ø Immutable simply means unmodifiable or unchangeable.

Ø Once string object is created its data or state can't be changed but a new string object is created with changes.

 

class String1

 {  

 public static void main(String args[])

  {  

    String s="Sachin";  

    s.concat(" Tendulkar");  

    System.out.println(s); // Sachin 

  }  

}  

 

 

 

Ø Here Sachin is not changed but a new object is created with Sachin Tendulkar. That is why string is known as immutable.

Ø As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".

Ø But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.

 

class String1

 {  

  public static void main(String args[])

   {  

     String s="Sachin";  

     s= s.concat(" Tendulkar");  

     System.out.println(s);// SachinTendulkar

  }  

}  

 

Reason: Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "sachin". If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

 

Ø For mutable strings, we can use StringBuffer and StringBuilder classes are used.

 

The methods of String Class are

Method Name

Description

Example

int   length()

returns string length

 

public int length() 

1. String s1="java";  

1. System.out.println("string length is: "+s1.length()); //4

2. 

3. System.out.println("string length is: "+”java”.length()); //4

char charAt(int index)

Extracts a single character from the string.

Returns char value for the particular index.

1. public char charAt(int index)  

 

 

1. String str="welcome";  

2. char ch=str.charAt(3); //c

 

String     substring(int beginIndex)

String     substring(int beginIndex, int endIndex)

 

Used to extract a substring from specified index from the main string.

Returns a substring.

String   s1="welcome"

String  str1= s1.substring(3); //come

String   str2 = s1.substring(3,5);

 //com

String   toLowerCase()

Returns a string in lowercase.

1. public String toLowerCase()  

 

1. String    s1="OBJECT oreinTED";  

2. String    str=s1.toLowerCase();  

3. System.out.println(str);  

4. //object oreinted

 

String  toUpperCase()

Returns a string in uppercase.

1. public String toUpperCase()  

 

5. String    s1="OBJECT oreinTED";  

6. String    str=s1.toUpperCase();  

7. System.out.println(str);  

8. //OBJECT  ORIENTED

 

void  getChars (int start, int end, char target[] , int tarstart)

 

Used to extract more than one character at a time.

Char buf[ ] = new char[10];

String str=”Welcome to Hyderabad”;

str.getChars(3,6,buf,0) //come

 

byte[]  getBytes()

Stores the characters in an array of bytes.

Strng str = new String(“Welcome to India”);

byte  b[ ] = str.getBytes();

char[]   toCharArray()

Converts all the characters ofA String object into a character array.

Strng str = new String(“Welcome to India”);

char ch[] = str.toCharArray();

 

 

String Comparison

boolean equals( Objectstr)

 

 

 

 

 

 

boolean  equalsIgnoreCase(String str)

 

 

 

 

boolean  startsWith()

 

 

 

 

boolean  endsWith()

 

 

 

 

 

 

 

equals()  versus   ==

 

 

 

 

 

 

 

 

 

 

int compareTo(String str )

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

int compareToIgnoreCase(String str )

 

 

 

 

 

Returns true if the strings contain same characters in same order otherwise returns false.

 

 

Compares two strings for equality and ignores the case differences.

 

 

Returns true, if the given string begins with a specified string.

 

 

 

Returns true, if the given string ends with a specified string.

 

 

 

equals() -> Compares the characters inside  a string object.

 

==  ->Compares two object references to see whether they refer to same instance.

 

 

 

 

Used to compare to strings.

It  returns

< 0:  The invoking string is less than the given string.

>0: The invoking string is

greater than the given string.

   0:  if the two strings are equal.

 

 

Same result as compareTo().

But ignores the case differences.

String   s1=”hello”;

String   s2=”hello”;

String   s3=”HELLO”;

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

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

//false

 

boolean x=s1.equalsIgnoreCase(s3));

//true

 

 

System.out.println(“welcome”.startsWith(“wel”)); //true

String str = new String(“Welcome”);

System.out.println(str.startsWith(“come”)); //false

 

System.out.println(“welcome”.endsWith(“wel”)); //false

 

String str = new String(“Welcome”);

System.out.println(str.endsWith(“come”)); //true

 

 

String s1 = new  “welcome”;

String  s2 = new String(s1);

String  s3= s1;

 

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

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

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

 

 

 

 

 

 

 

 

 

 

 

 

 

String s1 =”welcome”;

String s2= “hello”;

String s3 = “welcome”;

System.out.println(s1.compareTo(s3));    //0

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

System.out.println(s2.compareTo(s3));  // <0

 

 

 

String s1 =”welcome”;

String s3 = “WELcome”;

int x=s1.compareToIgnoreCase(s3));

//0

 

 

Searching Strings

 

int indexOf(int ch)

int indexOf(String str)

int indexOf(int ch , int start)

int indexOf(String str , int start)

int lastIndexOf(int ch)

int lastIndexOf(String str)

 

 

Used to search a string for a specified character or substring.

Returns index at which the character or string is found ,

Otherwise returns -1.

String str = “to do welcome to indian railways to come and well do of the rail works”

 

int x = str.indexOf(‘w’);

int x = str.indexOf(“wel”);

int x = str.indexOf(‘w’ , 10);

int x = str.lastIndexOf(‘r’);

 

 

 

 

Modifying  Strings

String substring(int start)

 

 

 

 

String substring(int start , int end)

 

 

String concat(String str)

 

 

 

String  replace(char old , char new)

 

 

 

 

 

 

String  trim()

 

 

 

 

 

+

To create a new copy of modified string the functions are used.

 

 

Returns a substring from specified index.

 

The two strings are concatenated.

 

 

Replaces all occurrences of one character in the invoking string with another character.

 

Returns a copy of invoking string from which any leading and trailing white space has been removed.

 

String concatenation

 

String   s1="welcome"

String   str1= s1.substring(3); //come

 

 

 

String   str2 = s1.substring(3,5);

 //com

 

 

String   s1 = “Welcome”;

String s2 = s1.concat(“To India”);

 

 

String   s1 = “Welcome”;

String s2 = s1.replace(‘e’ , ‘o’);

 

 

 

 

 

String   s1 = “  Welcome    ”;

String s2 = s1.trim(); //”welcome”

 

 

 

 

 

 

// String Concatenation

int  year=2019;

         String s2 = s1 +  "  " + year;

         System.out.println(s2);

         System.out.println(s2+2+2);

         System.out.println(s2+(2+2));

 

String toString()

Returns a String that contains the human readable form, which describes an object of a class.

String str=”Welcome to Hyd”;

String s = str.toString();

 

Box b1 = new Box();

String str = b1.toString();

 

 

boolean isEmpty()

Returns true if the string object is empty.

String s=””;

boolean x = s.isEmpty(); //true

String[] split(String  exp)

Returns a split string matching regular expression.

String str=”Welcome to Hyd for biryani”;

String  s[] = str.split(“\\s”);

Or

String  s[] = str.split(“ ”);

 

//splits string with white spaces.

 

 

 

 

//Converting String to particular type

public class  Demo

{

public static void main(String[] args)

{

String str1= "27";

//convert string to int

int x = Integer.parseInt(str1);

String str2= "345.67";

 //convert string to double

double d = Double.parseDouble(str2);

String str3="34.56";

 //convert string to float

 float f = Float.parseFloat(str3);

  String str4="4555526522426";

//convert string to long

  long y= Long.parseLong(str4);

 double res=  (d*y+x) / f;

  System.out.println("The result is " +res);

}

}

//String Operations

 

import java.io.*;

 

public class  StringOp1

{

public static void main(String[] args)

{

    // String length

String s1 = "Welcome to Java String Methods";

System.out.println("The no of characters are " + s1.length());

// String Concatenation

  int year = 2019;

  String s2 = s1 +  "  " + year;

 System.out.println(s2);

  System.out.println(s2+2+2);

   System.out.println(s2+(2+2));

 

 String str1= new String("Welcome");

 String s = str1.concat(" to India");

 System.out.println(s);

// Character Extraction

//String s1 = "Welcome to Java String Methods";

 

char ch1 = s1.charAt(3);

 System.out.println(ch1);

 

 char ch2[] = new char[5];

 s1.getChars(5,10,ch2,0);

 System.out.println(ch2);

 

 char ch3[ ] = new char[s1.length()];

 ch3 = s1.toCharArray();

 System.out.println(ch3);

 

          // String Comparisons

  String s3 = new String("WELCOME");

  String s4 = "WELCOME";

  String s5 = "welcome";

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

  System.out.println(s3.equals(s5));  //false

  System.out.println(s3.equalsIgnoreCase(s5)); //true

String s6 = s3;

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

  System.out.println(s3==s6); //true

 

  String s7 = "Food Time";

  System.out.println(s7.startsWith("Food")); //true

System.out.println(s7.endsWith("Time")); //true

System.out.println(s3.compareTo(s5));//-ve value

  //Searching Strings

 

System.out.println("The first occurance of l  is " + s1.indexOf('l'));

 System.out.println("The last occurance of l  is " + s1.lastIndexOf('l'));

 

System.out.println("The first occurance of l  is from 5 " + s1.indexOf('l',5));

  System.out.println("The last occurance of l  is from 5 " + s1.lastIndexOf('l',5));

System.out.println("The first occurance of me  is from 5 " + s1.indexOf("me",7))

 

System.out.println("The last occurance of me  is from 5 " + s1.lastIndexOf("me",7));

  //Modifying a string

  String str11 =  s1.substring(5);

String str22 = s1.substring(5, 15);

  System.out.println(str11);

System.out.println(str22);

 String str3 = s1.concat("Strings");

 System.out.println(str3);

String str4 =s1.replace("Java" , "Advanced Java");

System.out.println(str4);

 

String str5 = "      Welcome        ";

System.out.println(str5);

 System.out.println(str5.trim());

 

System.out.println(str5.toLowerCase());

System.out.println(str5.toUpperCase());  

 String s11 ="";

System.out.println(s11.isEmpty());

  String s22 = "welcome to India with love";

  String ss[ ]  = s22.split(" ");

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

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

}

}

//Program to use split() (Even Words list)

import java.util.*;

public class Task

{

public static void main(String args[])

{

Scanner sc = new Scanner(System.in);

System.out.println("Enter a line of Text");

String line = sc.nextLine();

String s[]= line.split(" ");

int count=0;

//for each loop

for(String word : s)

{

int len = word.length();

if(len % 2 == 0)

{

count++;

System.out.println(word + "    : " + len + "   : " +count);

}

}

}

}

 

 

 

 

StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

 

Constructors of StringBuffer Class

Constructor

Description

StringBuffer()

It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str)

It creates a String buffer with the specified string..

StringBuffer(int capacity)

It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class

Modifier and Type

Method

Description

public synchronized StringBuffer

append(String s)

It is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

public synchronized StringBuffer

insert(int offset, String s)

It is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.

public synchronized StringBuffer

replace(int startIndex, int endIndex, String str)

It is used to replace the string from specified startIndex and endIndex.

public synchronized StringBuffer

delete(int startIndex, int endIndex)

It is used to delete the string from specified startIndex and endIndex.

public synchronized StringBuffer

reverse()

is used to reverse the string.

public int

capacity()

It is used to return the current capacity.

public void

ensureCapacity(int minimumCapacity)

It is used to ensure the capacity at least equal to the given minimum.

public char

charAt(int index)

It is used to return the character at the specified position.

public int

length()

It is used to return the length of the string i.e. total number of characters.

public String

substring(int beginIndex)

It is used to return the substring from the specified beginIndex.

public String

substring(int beginIndex, int endIndex)

It is used to return the substring from the specified beginIndex and endIndex.

 

public class StringBufferExample {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("She sells sea shells ");

System.out.println("Given stringbuffer is: " + sb);

System.out.println("length of stringbuffer is: " + sb.length() + ", capacity of stringbuffer is: " + sb.capacity());

System.out.println("character at index 5 of the stringbuffer is: " + sb.charAt(5));

System.out.println("appendind the stringbuffer: " + sb.append("on the sea shore"));

System.out.println("substring of stringbuffer from index 10 to 20 is: " + sb.substring(10,20));

System.out.println("reverse of the stringbuffer is: " + sb.reverse());

}

}

 

String reverse example:

import java.util.Scanner;

 

public class StringReverse{

public static void main(String[] args){

Scanner in=new Scanner(System.in);

System.out.println("Enter the string to reverse: ");

    String str=in.nextLine();

StringBuffer sb= new StringBuffer(str);

    String reverse =sb.reverse().toString();

    System.out.println("String after reverse:"+reverse);

}

}

 

 

 

 

super 

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

 

class Animal{  

Animal(){System.out.println("animal is created");} 

String color="white";  

void eat(){System.out.println("Animal eating...");}  

}  

class Dog extends Animal{  

String color="black"

Dog(){  

super();  

System.out.println("dog is created");  

}  

 

void eat(){System.out.println("dog eating...");}  

void printColor(){  

System.out.println(color);//prints color of Dog class  

System.out.println(super.color);//prints color of Animal class  

super.eat();  

}  

}  

class TestSuper1{  

public static void main(String args[]){  

Dog d=new Dog();  

d.printColor();

d.eat();  

}} 

 

 

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a String into tokens.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens.

 

 

 

There are 3 constructors defined in the StringTokenizer class.

Constructor

Description

StringTokenizer(String str)

It creates StringTokenizer with specified string.

StringTokenizer(String str, String delim)

It creates StringTokenizer with specified string and delimiter.

StringTokenizer(String str, String delim, boolean returnValue)

It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class

Methods

Description

boolean hasMoreTokens()

It checks if there is more tokens available.

String nextToken()

It returns the next token from the StringTokenizer object.

String nextToken(String delim)

It returns the next token based on the delimiter.

boolean hasMoreElements()

It is the same as hasMoreTokens() method.

Object nextElement()

It is the same as nextToken() but its return type is Object.

int countTokens()

It returns the total number of tokens.

Example of StringTokenizer Class

import java.util.StringTokenizer;  

public class Simple{  

 public static void main(String args[]){  

   StringTokenizer st = new StringTokenizer("my name is khan"," ");  

     while (st.hasMoreTokens()) {  

         System.out.println(st.nextToken());  

     }  

   }  

}  

 

 

 

Eg:

import java.util.StringTokenizer;    

public class StringTokenizer1  

{    

 /* Driver Code */  

 public static void main(String args[])  

 {    

   /* StringTokenizer object */  

   StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class"," ");    

     /* Checks if the String has any more tokens */  

     while (st.hasMoreTokens())   

     {    

         System.out.println(st.nextToken());    

     }    

System.out.println(st.countTokens());

 }    

}  

 

 ingTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenizer class"," ");    

     /* Checks if the String has any more tokens */  

     while (st.hasMoreTokens())   

     {    

         System.out.println(st.nextToken());    

     }    

System.out.println(st.countTokens());

 }    

}  

 

 

Comments

Popular posts from this blog

Java Programming Preparation

Java Programming Syllabus