unit-i introduction to oop and java fundamentals

36
Unit-I INTRODUCTION TO OOP AND JAVA FUNDAMENTALS Program A program is nothing but a set of step-by-step instructions that only a computer can understand so that it can come up with a solution. There are different approaches to do that, which in technical term, are referred to as programming paradigms. Object Oriented Programming OOP refers to a programming methodology based on objects, instead of just functions and procedures. These objects are organized into classes, which allow individual objects to be group together. Difference between POP and OOP Procedure Oriented Programming Object Oriented Programming Divided Into In POP, program is divided into small parts called functions. In OOP, program is divided into parts called objects. Importance In POP,Importance is not given to data but to functions as well as sequence of actions to be done. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. Approach POP follows Top Down approach. OOP follows Bottom Up approach. Access Specifiers POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected, etc. Data Moving In POP, Data can move freely from function to function in the system. In OOP, objects can move and communicate with each other through member functions. Expansion To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function. Data Access In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data. Data Hiding POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding so provides more security. Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Examples Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, C#.NET.

Upload: others

Post on 29-Dec-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

Unit-I

INTRODUCTION TO OOP AND JAVA FUNDAMENTALS

Program

A program is nothing but a set of step-by-step instructions that only a computer can understand so

that it can come up with a solution. There are different approaches to do that, which in technical term, are

referred to as programming paradigms.

Object Oriented Programming

OOP refers to a programming methodology based on objects, instead of just functions and

procedures. These objects are organized into classes, which allow individual objects to be group together.

Difference between POP and OOP

Procedure Oriented Programming Object Oriented Programming

Divided

Into In POP, program is divided into small parts called functions.

In OOP, program is divided into parts called objects.

Importance In POP,Importance is not given

to data but to functions as well as sequence of actions to be done.

In OOP, Importance is given to the data

rather than procedures or functions because it works as a real world.

Approach POP follows Top Down approach. OOP follows Bottom Up approach.

Access

Specifiers POP does not have any access specifier. OOP has access specifiers named Public,

Private, Protected, etc.

Data

Moving In POP, Data can move freely from function to function in the system.

In OOP, objects can move and communicate with each other through member functions.

Expansion To add new data and function in POP is not so easy.

OOP provides an easy way to add new data and function.

Data Access In POP, Most function uses Global data for sharing that can be accessed freely

from function to function in the system.

In OOP, data can not move easily from function to function,it can be kept public or

private so we can control the access of data.

Data Hiding POP does not have any proper way for hiding data so it is less secure.

OOP provides Data Hiding so provides more security.

Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading.

Examples Example of POP are : C, VB, FORTRAN, Pascal.

Example of OOP are : C++, JAVA, VB.NET, C#.NET.

Differences between C++ and Java

Comparison Index C++ Java

Platform-

independent C++ is platform-dependent. Java is platform-independent.

Mainly used for C++ is mainly used for system programming.

Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile

applications,networking

Goto C++ supports goto statement. Java doesn't support goto statement.

Multiple

inheritance C++ supports multiple inheritance. Java doesn't support multiple inheritance

through class. It can be achieved

by interfaces in java.

Operator

Overloading

C++ supports operator

overloading.

Java doesn't support operator overloading.

Pointers C++ supports pointers. You can

write pointer program in C++.

Java supports pointer internally. But you

can't write the pointer program in java. It means java has restricted pointer support in java.

Compiler and

Interpreter C++ uses compiler only. C++ is compiled and run using compiler which converts source code into machine code so, C++ is platform dependent.

Java uses compiler and interpreter both. Java source code is converted into byte code at compilation time. The interpreter executes this byte code at run time and produces output. Java is interpreted that is why it is platform independent.

Call by Value

and Call by

reference

C++ supports both call by value and call by reference.

Java supports call by value only. There is no call by reference in java.

Structure and

Union

C++ supports structures and

unions.

Java doesn't support structures and unions.

Thread Support C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support.

Java has built-in thread support.

Documentation

comment C++ doesn't support documentation comment.

Java supports documentation comment (/** ... */) to create documentation for java

source code.

Virtual Keyword C++ supports virtual keyword so

that we can decide whether or not override a function.

Java has no virtual keyword. We can

override all non-static methods by default. In other words, non-static methods are virtual by default.

Hardware C++ is more nearer to hardware. Java is not so interactive with hardware.

Object oriented C++ is an partially object-oriented language.

Java is also an fully object-oriented language.

OOP Concepts

The main aim of object oriented programming is to implement real world entities

Object

Class

Abstraction

Encapsulation

Inheritance

Polymorphism

Object

Object can be defined as an instance of a class

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

Example: A dog is an object because it has states i.e. color, name, breed etc. as well as behaviors i.e. barking, eating etc. Object creation classname obj=new new classname();

Class

A class is a template or blueprint for an object which defines its states and behaviors.

Collection of objects of similar type.Class doesn’t store any space.

Class is a user defined data type.

Class definition

class classname

{

Data member;

Methods();

}

Abstraction

It refers to the act of representing essential feature without including the background

details.

Encapsulation

The wrapping up of data and methods into single unit.

Data is not accessible outside the class. This can be done access specifiers.

Provides the security that keeps data and methods safe from inadvertent changes.

A java class is the example of encapsulation

Inheritance

When one object (derived class) acquires all the properties and behaviors of parent object(base class), it is known as inheritance. It provides code reusability

Class subclass extents superclass

{ Datamember; Method(); }

Polymorphism (Poly refers to many)

The ability to take more than one form.

In java, we use method overloading and method overriding to achieve polymorphism. Example: class sum { int a,b,c; void getdata( int x,int y )

{ a=x; b=y; } void add() { c=a+b; System.out.println("Addition value"+c);

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

sum s=new sum(); s.getdata(10,20); s.add(); } } Characteristics of java

1) Simple

Java is very easy to learn and its syntax is simple, clean and easy to understand.

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

There is no need to remove unreferenced objects because there is Automatic Garbage Collection

in java. 2)Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured

because:

No explicit pointer

Java Programs run inside virtual machine sandbox.

3) Platform-independent. Java Language is platform-independent due to its hardware and software environment. 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 byte code and interpreter convert this byte code

into machine code.

This byte code is a platform independent code because it can be run on multiple platforms i.e. Write Once

and Run Anywhere(WORA).

4) Robust simply means strong.

Java is robust because:

It uses strong memory management.

There are lack of pointers that avoids security problems.

There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of

objects which are not being used by a Java application anymore.

There is exception handling and type checking mechanism in java. All these points makes java robust.

5)Architecture-neutral

Java is architecture neutral because there is no implementation dependent features e.g. size of primitive

types is fixed.

Java provides bug free system due to the strong memory management. 6)Portable

Java is portable because it facilitates you to carry the java bytecode to any platform.

7)High-performance

Java code is compiled into bytecode which is highly optimized by the Java compiler, so that the Java virtual machine (JVM) can execute Java applications at full speed. 8)Distributed

Java is distributed because it facilitates users to create distributed applications in java. RMI and EJB are used for creating distributed applications.. 9)Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads.

The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications etc.

10)Dynamic

Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded

on demand. It also supports functions from its native languages i.e. C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

JVM(Java Virtual Machine)

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

When you run the Java program, Java compiler first compiles your Java code to bytecode. Then, the JVM translates bytecode into native machine code

JRE

JRE (Java Runtime Environment) is a software package that provides Java class libraries, along with Java Virtual Machine (JVM), and other components to run applications written in Java programming. JRE is the superset of JVM.

JDK

JDK (Java Development Kit) is a software development kit to develop applications in Java. When

you download JDK, JRE is also downloaded, and don't need to download it separately. In addition to JRE, JDK also contains number of development tools (compilers, JavaDoc, Java Debugger etc). JRE contains JVM and other Java class libraries.

Over all Structure

Fundamental Programming Structures in Java

Documentation Section

Package Statement

Import Statements

Interface Statement

Class Definition

Main Method Class

Main Method Definition

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

{ /* Author:IT staff Date: 2018-04-28 Description:sample code */ public static void main(String[] args) { System.out.println("Hello Java");

} }

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 the starting point of the program.

String[] args is used for command line argument.

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

Java program execution

Steps For compile Java Program

First Save Java program with same as class name with .java extension. Example: Sum.java

Compile: javac Filename.java Example, javac Sum.java Steps For Run Java Program

Run by: java Filename

Example: java sum

DEFINING CLASSES IN JAVA The class is at the core of Java .A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword Syntax: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } //... type methodnameN(parameter-list) { // body of method } The data, or variables, defined within a class are called instance variables. The code is contained within methods. The methods and variables defined within a class are called members of the class. In most classes, the instance variables are acted upon and accessed by the methods defined for that class. 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. Thus, the data for one object is separate and unique from the data for another. A Simple Class class Rectangle { .int length, width; // Combined declaration void getData(int x , int y) { length = x ; width = y ; } int rectArea( ) { int area = length • width; retum(area); } } The class declaration only creates a template. It does not create an actual object. create object Syntax for Object creation classname referencevariable=new classname();

Example Rectangle rect1=new Rectangle(); // create a Rectangle object called rect1 Declaring Objects First, declare a variable of the class type. This variable does not define an object.Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. This is done using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated. Syntax: Rectangle rect1=new Rectangle(); Rectangle rect1; // declare reference to object rect1=new Rectangle();// allocate a Rectangle object The first line declares rect1 as a reference to an object of type Rectangle. At this point, rect1 does not yet refer to an actual object. The next line allocates an object and assigns a reference to it to rect1. After the second line executes, we can use rect1 as if it were a Rectangle object. But in reality, rect1 simply holds, in essence, the memory address of the actual Rectangle object.

Assigning Object Reference Variables Syntax: Rectangle R1 = new rectangle(); Rectangle R2= R1; R2 is being assigned a reference to a copy of the object referred to by R1. R1 and R2 will both refer to the same object. The assignment of R1 to R2 did not allocate any memory or copy any

part of the original object. It simply makes R2 refer to the same object as does R1. Thus, any changes made to the object through R2 will affect the object to which R1 is referring, since they are the same object.

Example1 :

class Rectangle { int length, width; void getData(int x, int y) { length = x;

width = y; } int rectArea () { int area = length * width; return (area); } }

class RectArea { public static void main(String args[ ] ) { int areal,area2; Rectangle rect1 = new Rectangle(); Rectangle rect2 = new Rectangle();

rect1. length = 15; rect1. width = 10; areal = rect1.length * rect1. width; rect2.getData(20,12); area2 = rect2.rectArea(); System.out.println("Areal = " + areal);

System.out.println("Area2 = " + area2); } }

Example2

class Box { double width; double height; double depth; } class BoxDemo2 {

public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; mybox1.width = 10; // assign values to mybox1's instance variables mybox1.height = 20; mybox1.depth = 15;

mybox2.width = 3; //assign different values to mybox2's instance variables mybox2.height = 6; mybox2.depth = 9; vol = mybox1.width * mybox1.height * mybox1.depth; // compute volume of first box System.out.println("Volume is " + vol); vol = mybox2.width * mybox2.height * mybox2.depth; // compute volume of second box System.out.println("Volume is " + vol); }

}

Scanner class

Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program

Java Scanner Methods to Take Input

The Scanner class provides various methods that allow us to read inputs of different types.

Method Description

nextInt() reads an int value from the user

nextFloat() reads a float value form the user

nextBoolean() reads a boolean value from the user

nextLine() reads a line of text from the user

next() reads a word from the user

nextByte() reads a byte value from the user

nextDouble() reads a double value from the user

nextShort() reads a short value from the user

nextLong() reads a long value from the user

Example

// Java program to read data of various types using Scanner class. import java.util.Scanner; public class ScannerDemo1

{ public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in);

// String input String name = sc.nextLine(); // Character input char gender = sc.next().charAt(0); // Numerical data input // byte, short and float can be read

// using similar-named functions. int age = sc.nextInt(); long mobileNo = sc.nextLong();

double cgpa = sc.nextDouble(); // Print the values to check if the input was correctly obtained. System.out.println("Name: "+name);

System.out.println("Gender: "+gender); System.out.println("Age: "+age); System.out.println("Mobile Number: "+mobileNo); System.out.println("CGPA: "+cgpa); } }

Constructors in Java

A constructor is a special method that is used to initialize an object

A constructor doesn’t have a return type.

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

Constructors are not considered members of a class.

A constructor is called automatically when a new instance of an object is created.

Constructor in Java cannot be abstract, static, final or synchronized. Syntax

public class MyClass { //This is the constructor MyClass() { } .. }

Types of java constructors

There are two types of constructors in java:

Default constructor (no-arg constructor)

Parameterized constructor

Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter. Syntax: classsample { sample() {

System.out.println("default"); } public static void main(String args[]) { sampleb=new sample(); } } Parameterizedconstructor

A constructor which has a specific number of parameters is called parameterized constructor.

Parameterized constructor is used to provide different values to the distinct objects. Example: class Student{ int id;

String name; Student(inti,String n) { id = i;

name = n; } void display() { System.out.println(id+" "+name); } public static void main(String args[])

{ Student s1 = new Student(111,"ram"); Student s2 = new Student(222,"raju"); s1.display(); s2.display(); } } Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are:

assigning the values of one object into another clone() method of Object class Example

class Student

{ int id; String name; Student(inti,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(111,"rajesh"); Student s2 = new Student(s1);

s1.display(); s2.display(); }

} Constructor Overloading

Constructor overloading is a technique of having more than one constructor with different parameter lists Example

class Student { int id; String name; int age; Student(inti,String n) { id = i;

name = n; } Student(inti,Stringn,int a){ id = i; name = n; age=a; }

void display() { System.out.println(id+" "+name+" "+age); } public static void main(String args[]) { Student s1 = new Student(111,"suresh");

Student s2 = new Student(222,"durai",25); s1.display(); s2.display(); } } Methods in java

Modifier-: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers. return type : The data type of the value returned by the the method or void if does not return a value.

Method Name : the rules for field names apply to method names as well, but the convention is a little different. Parameter list : Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses (). Exception list : The exceptions you expect by the method can throw, you can specify these exception(s). Method body : it is enclosed between braces. The code you need to be executed to perform your intended operations.

Method call

Method definition // Program to illustrate methodsin java

import java.io.*; class Addition { int sum = 0; publicint add(int a, int b) //Method definition { // adding two integer value.

sum = a + b; //returning summation of two values. return sum; } } classSample { public static void main (String[] args)

{ Addition a = new Addition(); // creating an instance of Addition class int s = a.add(1,2); //Method call System.out.println("Sum of two integer values :"+ s); } }

Method overloading

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.Method overloading increases the readability of the program. Different ways to overload the method

There are two ways to overload the method in java

By changing number of arguments

By changing the data type

Example:

class OverloadDemo { void area(float x) { System.out.println("the area of the square is "+x*x);

} void area(float x, float y) { System.out.println("the area of the rectangle is "+x*y); } void area(double x) {

double z = 3.14 * x * x; System.out.println("the area of the circle is "+z); } }

class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); ob.area(5); ob.area(11,12); ob.area(2.5);

} } Modifiers in java

There are two types of modifiers in java:

access modifiers

non-access modifiers. Access modifiers

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

Access specifiers provide the access control and it illustrates the concept of encapsulation There are 4 types of java access modifiers:

private

default

protected

public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. private access modifier

The private access modifier is accessible only within class. Example

class A

{ Private int data=40; private void msg() { System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){

A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error }}

Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class.

Example: class A

{ private A() { //private constructor

} void msg(){System.out.println("Hello"); } } public class Simple { public static void main(String args[]) {

A obj=new A();//Compile Time Error } } Default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package. Example

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package. //save by A.java package pack; class A {

void msg() { System.out.println("Hello");} } //save by B.java packagemypack; import pack.*;

class B { public static void main(String args[]) { A obj = new A();//Compile Time Error obj.msg();//Compile Time Error }

} In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

Protected Access Modifier

Protected data member and method are only accessible by the classes of the same package and the subclasses present in any package.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. Example:

//save by A.java package pack; public class A{ protected void msg(){System.out.println("Hello");}

} //save by B.java package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B();

obj.msg(); } } Public access modifier

The members, methods and classes that are declared public can be accessed from anywhere. This modifier doesn’t put any restriction on the access. Example

//save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java

package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }

The scope of access modifiers in tabular form

Access Specifier Within class Within package Outside package Outside package within subclass non subclass

Private Yes No No No

Default Yes Yes No No

Protected Yes yes yes No

Public Yes yes yes Yes

Static Keyword

Static members are common for all the instances (objects) of the class.

Static members belong to the class instead of a specific instance, this means if you make a member static, you can access it without object. The static can be:

o variable (also known as class variable) o method (also known as class method) o block o nested class

Static variable

Single copy of static variable is created and shared among all the instances of the class.

Memory allocation for such variables only happens once when the class is loaded in the memory. Static method

A static method can be invoked without the need for creating an instance of a class.

The static method can not use non static data member or call non-static method directly.

this and super cannot be used in static context. Static block

Used to initialize the static data member.

It is executed before main method at the time of class loading. class UseStatic

{ static int a = 3; //Static variable static int b; static void meth(int x) // Static method { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b);

} static // Static block { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) {

meth(42); } } Output : Static block initialized. x = 42 a = 3

b = 12 Static nested class

It is possible to make a class static, but only inner class can be declared as static. A Outer class can not be declared as static.

Static classes are required when you want to create object of inner class to access their methods

without creating object of outer class. Example:

class Outerclass { static int data=30; static class Innerclass

{ void msg() { System.out.println("data is "+data);

} } public static void main(String args[]) { Outerclass. Innerclass obj=new Outerclass. Innerclass (); obj.msg(); } }

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. Types of Java Comments

Single Line Comment

The single line comment is used to comment only one line. Syntax // This is single line comment

Multi Line Comment

The multi line comment is used to comment multiple lines of code. Syntax:

/* This is multi line comment */

Example:

public class CommentExample2 { public static void main(String[] args) { /* Let's declare and print variable in java. */ int i=10; System.out.println(i); //print the value of i

} }

Data Types in Java

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store

integers, decimals, or characters in these variables.

In java, there are two types of data types primitive data types non-primitive data types

Data Type Size

Boolean 1 bit

Char 2 byte

Byte 1 byte

Short 2 byte

Int 4 byte

Long 8 byte

Float 4 byte

Double 8 byte

Variables in java

Variable is a name of memory location. There are three types of variables:

Local

Instance

Static.

Local variables:

Local variables are declared in methods, constructors, or blocks. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor or block. The variable will be declared and initialized within the method and the variable will be

destroyed when the method has completed Instance Variable

Instance variables are variables within a class but outside any method.

These variables are initialized when the class is instantiated.

Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

Static variable

Also called class variables

Single copy of static variable is created and shared among all the instances of the class.

Memory allocation for such variables only happens once when the class is loaded in the memory. Arrays in java

Array is a group of variables of same datatypes and referred to by a common name. Array is a contiguous block of memory location and referred by a common name.

Two methods of declaration: Method1: datatype[]variable_name=new datatype[SIZE]; Eg.int[] myarray=new int[10];

Method 2: datatypevariable_name[ ]= {values}; Eg.intmyarray[]={5,6,7,8,9}; Two types of array:

One dimensional array. Two dimensional array. Multi dimensional array

ONE DIMENSIONAL ARRAYS: It is a list of variables of same datatype. Sample Programs:

//sorting a one dimensional Array import java.util.Arrays; public class arraysort{

public static void main(String[] args){ int num[] = {50,20,45,82,25,63}; int l = num.length; int i,j,t; System.out.print("Given number : "); for (i = 0;i <l;i++ ){ System.out.print(" " + num[i]); }

System.out.println("\n"); System.out.print("Ascending order number : "); Arrays.sort(num);

for(i = 0;i <l;i++) { System.out.print(" " + num[i]); } } }

TWO DIMENSIONAL ARRAYS: Two dimensional arrays are similar to a matrix with a set of rows and columns. Matrix Multiplication: class MatrixMultiply{ public static void main(String[] args) { int array[][] = {{5,6,7},{4,8,9}}; int array1[][] = {{6,4},{5,7},{1,1}}; int array2[][] = new int[3][3];

System.out.println("Matrix 1 : "); for(int i = 0; i < array.length; i++) { for(int j = 0; j < array[i].length; j++) { System.out.print(" "+ array[i][j]); } System.out.println(); }

System.out.println("Matrix 2 : "); for(int i = 0; i < array1.length; i++) { for(int j = 0; j < array1[i].length; j++) { System.out.print(" "+array1[i][j]); } System.out.println(); } for(int i = 0; i < array.length; i++) {

for(int j = 0; j < array1[j].length ; j++) { array2[i][j]=0; for(int k = 0; k < array1.length; k++){ array2[i][j] += array[i][k]*array1[k][j]; } } } System.out.println("Multiply of both matrix : ");

for(int i = 0; i < array.length; i++) { for(int j = 0; j < array1[j].length; j++) { System.out.print(" "+array2[i][j]); } System.out.println(); } }}

THREE DIMENSIONAL ARRAYS:

import java.util.*; class threed { public static void main(String arg[]) { int arr[][][]={{{1,2},{3,4},{4,5}},{{5,6},{7,8},{9,10}}};

int i,j,k; System.out.println("Elements"); for(i=0;i<arr.length;i++)

{ System.out.println("2D array elements"+(i+1)); for(j=0;j<arr[i].length;j++) {

for(k=0;k<arr[i][j].length;k++) System.out.print(" "+arr[i][j][k]); System.out.println(""); } System.out.println("\n");}}}}

Operators in java

Operator in java is a symbol that is used to perform operations. o Assignment Operators = o Arithmetic Operators - + * / % ++ -- o Relational Operators > < >= <= == != o Logical Operators && || & | ! ^ o Bit wise Operator & | ^ >> >>> o Compound Assignment Operators += -= *= /= %= <<= >>= >>>=

o Conditional Operator ?: o Instance of operator

ArithmeticOperators

public class ArithmeticOperatorsExample {

public static void main(String[] args) { System.out.println("Arithmetic operators example :"); int i = 50 + 20; int j = i - 10; int k = j * 2; double l = k / 6;

System.out.println("i = " + i); System.out.println("j = " + j); System.out.println("k = " + k); System.out.println("l = " + l); }

}

Relational Operators

public class Test { public static void main(String args[]) { int a = 10;

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

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

} } output: a == b = false a != b = true a > b = false a < b = true

b >= a = true b <= a = false

Logical Operators

public class Test { public static void main(String args[]) { boolean a = true;

boolean b = false; System.out.println("a && b = " + (a&&b)); System.out.println("a || b = " + (a||b) ); System.out.println("!(a && b) = " + !(a && b));

} }

Output: a && b = false a || b = true !(a && b) = true

Bit wise Operator

public class Test { public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0;

c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c ); c = a | b; /* 61 = 0011 1101 */ System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */ System.out.println("~a = " + c ); c = a << 2; /* 240 = 1111 0000 */

System.out.println("a << 2 = " + c ); c = a >> 2; /* 215 = 1111 */ System.out.println("a >> 2 = " + c ); c = a >>> 2; /* 215 = 0000 1111 */ System.out.println("a >>> 2 = " + c ); }

} Output: a & b = 12 a | b = 61 a ^ b = 49 ~a = -61

a << 2 = 240 a >> 15 a >>> 15

Conditional operator

public class Test {

public static void main(String args[]){ int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b );

} }

Output:

Value of b is : 30 Value of b is : 20

instanceof operator The instanceof operator is used to test whether the object is an instance of the specified type

(class or subclass or interface).

public class Test {

public static void main(String args[]){ String name = "James"; // following will return true since name is type of String

boolean result = name instanceof String; System.out.println( result ); } }

Output:

True Compound operators:

public class CompoundOperatorsDemo { public CompoundOperatorsDemo() { int x = 0, y = 5; x += 3; System.out.println("x : " + x); y *= x;

System.out.println("y : " + y); } public static void main(String args[]) { new CompoundOperatorsDemo(); } }

control statements

A program executes from top to bottom except when we use control statements, we can control

the order of execution of the program, based on logic and values. Decision-making statements

if

if-else,

if-else-if

switch Looping statements

for while

do-while Branching statements

break

continue,

Decision-making statements

If :

If the condition stated in the parentheses evaluates to true, then the statements are executed, otherwise the statements in the if block are skipped.

if ( condition ) { // code }

example

if ( wish == true ) { System.out.println("Hi"); }

if-else

The if statement is known as a single selection structure since we have only a single statement that is either executed or not. No alternative statement would be executed if the condition evaluates to false. if ( condition ) {

// code } else { // code } Example

if ( num%2==0){ System.out.println("Number is even");

}else{ System.out.println("Number is odd"); } if-else- if

Whenever the condition is true, the associated statement will be executed and the remaining conditions will be bypassed. If none of the conditions are true then the else block will execute.

if(condition)

statements;

else if (condition)

statements;

else if(condition)

statement;

else

statements;

Example

if (num == 1) { System.out.println("One"); } else if (num == 2) { System.out.println("Two"); } else if (num == 3) { System.out.println("Three");

} else { System.out.println("Numbers greater than three cannot be processed by this code"); } The Switch Statements The switch statement is a multi-way branch statement. The switch statement of Java is another selection statement that defines multiple paths of execution of a program. It provides a better alternative than a large series of if-else-if statements.

public class SwitchDemo { public static void main( String[] args ) { int age; Scanner inputDevice = new Scanner( System.in ); System.out.print( "Please enter Age: " ); age = inputDevice.nextInt();

switch ( age ) { case 18:

System.out.println( "age 18" ); break; case 19: System.out.println( "age 19" );

break; default: System.out.println( "not matched" ); break; } } }

Looping statements

While

Entry level checking

If the condtion is true then loop will executed

The syntax of a while loop is: while(Boolean_expression)

{ //Statements } Example

public class Test { public static void main(String args[]) { int x = 10;

while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } } Do- while loop

Exit level checking

Loop will executed once even if the condition become false The syntax of a do...while loop is: do

{ //Statements }while(Boolean_expression); Example

public class Test { public static void main(String args[]){ int x = 10; do{

System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } } For loop

The syntax of a for loop is: for(initialization; Boolean_expression; update) {

//Statements } Example

public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n");

} } } The syntax of enhanced for loop is: for(declaration : expression) { //Statements

}

Example

public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){

System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); }

} } Branching statements

Break:

The break keyword is used to stop the entire loop. The break keyword must be used inside any

loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line

of code after the block. Syntax: The syntax of a break is a single statement inside any loop: break;

Example: public class Test { public static void main(String args[]) {

int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { break;

} System.out.print( x ); System.out.print("\n"); } } } This would produce the following result: 10 20

continue: The continue keyword can be used in any of the loop control structures. It causes the loop to

immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression. Syntax: The syntax of a continue is a single statement inside any loop: continue;

Example: public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; }

System.out.print( x ); System.out.print("\n"); } } } This would produce the following result: 10

20 40 50

Packages in java

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, o built-in package o user-defined package.

Java package provides access protection.

Java package removes naming collision.

Built-in package

User defined package:

Package creation:

Package packagename;

Example:

package mypack; public class Simple { public static void main(String args[]) { System.out.println("Welcome to package"); }

} Three ways to Access the package from another package:

1. import package.*; 2. import package.classname; 3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not

subpackages. The import keyword is used to make the classes and interface of another package accessible to

the current package. //save by A.java package pack; public class A {

public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{

public static void main(String args[]){ A obj = new A(); obj.msg(); }

} 2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example

//save by A.java package pack; public class A { public void msg()

{System.out.println("Hello"); } } //save by B.java package mypack; import pack.A;

class B { public static void main(String args[]) { A obj = new A(); obj.msg(); }

} 3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.

Example

//save by A.java

package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; class B{

public static void main(String args[]){ pack.A obj = new pack.A();//using fully qualified name obj.msg(); } }

Import static members

Import static MyPackage.A.display(); // Import static members(display() only) in that package

Import static MyPackage.A.*; // Import All static members in that package

Example:

import static java.lang.System.*; class Example{ public static void main(String args[]){

out.println("Hello");//Now no need of System.out out.println("Java"); } } Sub packages in Java

A package inside another package is known as sub package Syntax: package Mainpack.subpack;

Example:

import package.subpackage; //creation of subpackage public class HelloWorld { public void show(){ System.out.println("This is the function of the class HelloWorld!!"); }

} import package.subpackage.*; //import subpackage class CallPackage{ public static void main(String[] args){ HelloWorld h2=new HelloWorld(); h2.show(); }

} Javadoc Comments

Javadoc is a documentation generator for the Java language for generating API documentation in HTML format from Java source code

Javadoc comments can be placed before any class, field, or method declaration

JavaDoc comment blocks begin with /** and ends with */

lines of JavaDoc comments begin, by convention, with *; Some Javadoc tags

JavaDoc Tag Meaning Description

@see Name of associated class Class, method

@author Author Class

@version Version Class

@param Input parameters Method

@return Return value Method

@exception Generated exception Method

@throws Generated exception Method

@deprecated Defines the element as deprecated

Class, method

@since The API version in which this element was included

Class, method

Example: package Ex2; /** * Java class example

* The class illustrates how to write comments used to generate JavaDoc documentation * @author MANIKANDAN */ public class sum { public int a,b,c; /** * Simple method example. * The methods adds 2 numbers and return the result

* @param x the first value * @param y the second value * @return Sum between x and y * @see sum */ public int add(int x,int y) { c=x+y;

return c; //System.out.println("Addition value"+c); } } public class Addition {

public static void main(String A[]) { int z; sum s=new sum(); z=s.add(10,20); System.out.println("Addition value"+z); } }