Programming Paradigms : Programming is a creative process carried out by programmers to instruct a computer on how to do a task. A program is a set of instructions that tells a computer what to do in order to come up with a solution to a particular problem. There are a number of alternative approaches to the programming process, referred to as programming paradigms. Different paradigms represent fundamentally different approaches to building solutions to specific types of problems using programming. Most programming languages fall under one paradigm, but some languages have elements of multiple paradigms. Two of the most important programming paradigms are the procedural paradigm and the object-oriented paradigm.
Procedural Programming Procedural Programming: It can be defined as a programming model which is derived from structured programming, based upon the concept of calling procedure. Procedures, also known as routines, subroutines or functions, simply consist of a series of computational steps to be carried out. During a program’s execution, any given procedure might be called at any point, including by other procedures or itself . Languages used in Procedural Programming: FORTRAN, ALGOL, COBOL, BASIC, Pascal and C. *
Object Oriented Programming Object Oriented Programming: It can be defined as a programming model which is based upon the concept of objects. Objects contain data in the form of attributes and code in the form of methods. In object oriented programming, computer programs are designed using the concept of objects that interact with real world. Object oriented programming languages are class-based, meaning that objects are instances of classes, which also determine their types . Languages used in Object Oriented Programming: Java, C++, C#, Python, PHP, JavaScript, Objective-C. *
Procedural Programming Object-Oriented Programming In procedural programming, the program is divided into small parts called functions . In object-oriented programming, the program is divided into small parts called objects . Procedural programming follows a top-down approach . Object-oriented programming follows a bottom-up approach . There is no access specifier in procedural programming. Object-oriented programming has access specifiers like private, public, protected, etc. Adding new data and functions is not easy. Adding new data and function is easy. Procedural programming does not have any proper way of hiding data so it is less secure . Object-oriented programming provides data hiding so it is more secure . In procedural programming, overloading is not possible. Overloading is possible in object-oriented programming. Difference Between Procedural and Object-Oriented Programming
In procedural programming, the function is more important than the data. In object-oriented programming, data is more important than function. Procedural programming is based on the unreal world . Object-oriented programming is based on the real world . In procedural programming, there is no concept of data hiding and inheritance. In object-oriented programming, the concept of data hiding and inheritance is used. Procedural programming is used for designing medium-sized programs. Object-oriented programming is used for designing large and complex programs. Procedural programming uses the concept of procedure abstraction. Object-oriented programming uses the concept of data abstraction. Code reusability absent in procedural programming, Code reusability present in object-oriented programming. Examples: C, FORTRAN, Pascal, Basic, etc. Examples : C++, Java, Python, C#, etc.
Modular Programming Modular programming is the process of subdividing a computer program into separate sub-programs. A module is a separate software component. It can often be used in a variety of applications and functions with other components of the system . Some programs might have thousands or millions of lines and to manage such programs it becomes quite difficult as there might be too many of syntax errors or logical errors present in the program, so to manage such type of programs concept of modular programming approached. Each sub-module contains something necessary to execute only one aspect of the desired functionality. Modular programming emphasis on breaking of large programs into small problems to increase the maintainability, readability of the code and to make the program handy to make any changes in future or to correct the errors.
Advantages of Using Modular Programming Approach – Ease of Use : This approach allows simplicity, as rather than focusing on the entire thousands and millions of lines code in one go we can access it in the form of modules. This allows ease in debugging the code and prone to less error . Reusability : It allows the user to reuse the functionality with a different interface without typing the whole program again . Ease of Maintenance : It helps in less collision at the time of working on modules, helping a team to work with proper collaboration while working on a large application.
Example: // assumes all grades are for courses with same num of credits double calculateGradeAverage (double[] grades) { double sum = 0; for ( int i=0; i < grades.length ; i++) // sum all grades sum = sum + grades[i]; return (sum/ grades.length ); // calculate average } This program fragment is a Java method called calculateGradeAverage that gets as input a list of grades , using an array of data type double and returns the calculated average also as double. In the method, we initialize the local variable sum to 0, and then using a for-loop, we add all the grades to sum . Lastly, we divide the obtained sum by the number of grades and return the value to the caller of this method. If our input array had the grades 3.5, 3.0, 4.0 , after adding them sum would have the value 10.5 and then it would be divided by 3 since there are three grades. The method would return the value 3.5 .
Generics means parameterized types . The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity. Generic Programming :
How Do Generics Work In Java? Java Generics allow you to include a parameter in your class/method definition which will have the value of a primitive data type . For Example: you can have a Generic class “Array” as follows: Class Array<T> {….} Where <T> is the parameterized type. Next, you can create objects for this class as follows: Array int_array <Integer> = new Array<Integer> () Array<Character> char_array = new Array<Character> (); So given a Generic parameterized class, you can create objects of the same class with different data types as parameters. This is the main essence of using Java Generics.
Generic Classes A Generic class is the same as a normal class except that the classname is followed by a type in angular brackets. A general definition of a Generic class is as follows: class class_name <T> { class variables; ….. class methods; } Once the class is defined, you can create objects of any data type that you want as follows: class_name <T> obj = new class_name <T> (); For Example, for Integer object the declaration will be: class_name <Integer> obj = new class_name <Integer>; Similarly, for the String data type, the object will be: class_name <String> str_Obj = new class_name <String>;
Java Generics Method Similar to the generics class, we can also create a method that can be used with any type of data. Such a class is known as Generics Method.
class Main { public static void main(String[] args ) { // initialize the class with Integer data DemoClass demo = new DemoClass (); // generics method working with String demo.<String> genericsMethod ("Java Programming"); // generics method working with integer demo.<Integer> genericsMethod (25); } } class DemoClass { // creae a generics method public <T> void genericsMethod (T data) { System.out.println ("Generics Method:"); System.out.println ("Data Passed: " + data); } }
Generics Method: Data Passed: Java Programming Generics Method: Data Passed: 25 OUTPUT: public <T> void genericMethod (T data) {...} Here, the type parameter <T> is inserted after the modifier public and before the return type void . We can call the generics method by placing the actual type <String> and <Integer> inside the bracket before the method name. demo.<String> genericMethod ( "Java Programming" ); demo.<Integer> genericMethod ( 25 ); In the above example, we have created a generic method named genericsMethod .
Class A class is a collection of instance variables and methods. instance variables are the variables defined in the class and methods are the functions defined in the class. Syntax : class classname { access_specifier type instance_variable =value; access_specifier returntype methodname ([ type para1,…]) { //body of method } ………… }
Example : Class Studentdetails { p ublic int roll_no ; p rotected String name; void display() { System.out.println (name); System.out.println ( roll_no ); } }
1)Creation of class is no use if objects are not constructed.Because class does not occupy memory.To make use of a class ,object should be created because objects are the actual variables which occupy memory in ram . 2)Creation of classes is nothing but creation of userdefined datatype.We can use this new datatype (class) to create variables of the class type
object An object is an instantiation or implementation of class. It contains variables and functions. Syntax: classname objectname =new classname (); classname objectname ;//Here objectname is a reference variable of classname . The new operator allocates memory of classname () dynamically which is said to be an object and whose address is assigned to reference variable. Example : Studentdetails obj =new Studentdetails ();
Creation of classes is nothing but creation of userdefined datatype.We can use this new datatype (class) to create variables of the class type . How ever creating objects of a class is a two step process. First we must declare a reference variable of the class.This reference variable does not define an objects,instead it creates a variable that stores reference(address) of an object.
Accessing class members Syntax for accessing instance variable of a class: objectname . instance variable ; Ex: obj.name ; Syntax for accessing methods of a class: objectname.method (arguments list……); Ex: obj.display ();
class Studentdetails { int roll_no =501; String name=" sai "; public void display() { System.out.println (name); System.out.println ( roll_no ); } } class Student { public static void main(String args []) { Studentdetails obj =new Studentdetails (); obj.display (); } } n ame r oll_no display () obj memory 1001 1001 Reference Variable Object
Encapsulation Binding (or wrapping) code and data together into a single unit are known as encapsulation . A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Example 1)In pop, program is divided into small parts called function . 1)In oop , program is divided into small parts called object.
Abstraction : Abstraction : Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user Hiding internal details and showing functionality is known as abstraction. In Java, we use abstract class and interface to achieve abstraction .
Example: abstract class sample { abstract void display( int a); } Class A extends sample { void display( int a) { x=a; System.out.println (x); } } class ex{ public static void main(string args []); A obj =new A(); obj.display (20); } }
DATA HIDING Example: class sample { private int x; public void display( int a) { x=a; System.out.println (x); } } class ex {public static void main(string args []); sample obj =new sample(); obj.display (20); } }
structure str { int roll_no ; char name[20]; }; C Structure C++ Structure structure str { int roll_no ; char name[20]; member function(); };
Ex:int a=10; Ex:int a[3]; a[0]=10; a[1]=20; a[2]=30; structure str { char name[20]; int id; }; str name id
Inheritance Inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class. The class which inherits the members of another class is called derived class and the class whose members are inherited is called base class.
1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details Bank in 90’s Bank in 20’s 1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details + 5.online money Transfer 6.Online pay cheques 7.Use of Debit/Credit cards With out Inheritance Class B Class A
1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details Bank in 90’s Bank in 20’s 1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details + 5.online money Transfer 6.Online pay cheques 7.Use of Debit/Credit cards With out Inheritance Class B Class A
1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details Bank in 90’s Bank in 20’s 1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details + 5.online money Transfer 6.Online pay cheques 7.Use of Debit/Credit cards With Inheritance Class B Class A
1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details Bank in 90’s Bank in 20’s 1.Add money 2.Withdraw money 3.Take loan 4.Display Account Details + 5.online money Transfer 6.Online pay cheques 7.Use of Debit/Credit cards With Inheritance Class B Class A
Example : class A { int x=10; } class B extends A { System.out.println (x); } B A x=10
Polymorphism When one task is performed by different ways i.e. known as polymorphism. In JAVA, we use Function overloading and Function overriding to achieve polymorphism . Example: v oid area ( int s) { System.out.println (s); } void area ( int l ,int b) { System.out.println (l*b); }
It is the concept of binding of function call with the address of called function. This binding can be of two types they are compile time binding and dynamic binding. c lass A { v oid sum( int x,int y) { System.out.println ( x+y ); } } class B { p ublic static void main(String args []) { A obj =new A(); o bj.sum(2,4); } } Dynamic binding
Objects communicate with one another by sending and receiving information. A single object by itself may not be very useful. An application contains many objects. One object interacts with another object by invoking methods on that object. It is also referred to as Method Invocation . Message passing
Documentation section Package statement Import Statement Interface Statement Class Definitions Main method class { Main method definition } Structure/Creation of java Program
Documentation section :this section contains set of comment line ,comment is used for giving the name of the program and author & other details. There are two types of comment 1)Single line comment(//) 2)multiline /**…. ….. ….*/ Package statement :this statement declares apackage name and informs the compiler that classes defined here belonging to this package. Import statement :this import statement is similar to the #include statement in c.
Interface statement: An interface is like a class but includes a group of method declaration. Class definations :java program may have number of classes of which only one class defines a main method. Main method :every java program execution starts from main method .this class is the essential part of the java program.
HelloWorld program // HelloWorld program public class HelloWorld { public static void main(String[] args ) { System.out.println ("Hello, World!"); } } Class declaration: A class declaration includes name and visibility of the class. * 45 Java Programming Skills
HelloWorld program specification public : This is access modifier which is used to define visibility. Here main method will be visible to all other classes. static : static members belongs to class rather than any specific object. It simply means you can access the static members without object . void : void is another keyword which defines return type of main method. It simply means main method does not return anything before terminating the program. main : main is method name here. String args[]: You can pass arguments to java program using args[] array. It is used to take user input using command line. *
Compilation & execution: command prompt Compile C:\MyJava> javac HelloWorld .java 47 HelloWorld.java javac HelloWorld.class compilation Byte code Source code Platform specific code java execution Save the file as HelloWorld.java. A public class must be saved in the same name as class name. Execute C:\MyJava> java HelloWorld * Java Programming Skills
Features/buzzwords of Java Simple: Java is easy to learn. It does not include concepts of pointers and operator overloading that were available in C++. Platform independence: Java is write-once, run-anywhere (WORA) language. Once you compile java code, you can run it on any machine. *
Features/buzzwords of Java Portable: Java bytecode can be portable to any platform and can be executed on any platform. High performance: Java is interpreted language but it has provided Just in time (JIT) compiler to increase performance. Object Oriented: You can model everything into an object which has data and behavior. Java has incorporated various object-oriented concepts such Abstraction , Encapsulation , Polymorphism , and inheritance. *
Features/buzzwords of Java Multi-threading: Java has provided multi-threading feature which will help you to execute various task in parallel. It does not occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,window-based, and Web-based applications, etc. Secured: Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because: No explicit pointer and Java Programs run inside a virtual machine sandbox . Java Runtime Environment(JRE) which is used to load Java classes into the Java Virtual Machine dynamically. *
Features/buzzwords of Java Robust: (Robust means strong) Java uses strong memory management. There is a lack of pointers that avoids security problems. There is automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore. There are exception handling and the type checking mechanism in Java. All these points make Java robust. *
Features/buzzwords of Java Distributed : Java facilitates users to create distributed applications by using RMI and EJB . This feature of Java makes us able to access files by calling the methods from any machine on the internet. Compile & Interpreted: Basically a computer programming language is either compiled or interpreted. But Java uses both compiler & interpreter. Initially java compiler (javac) translates source code into byte code and after that java interpreter (java) generates machine code that can be directly executed. *
Features/buzzwords of Java Architecture-neutral: Java is architecture neutral because there are no implementation dependent features , for example, the size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java . Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It supports automatic memory management (garbage collection). *
Data types Data types refer to type of data that can be stored in variable. As Java is strongly typed language, you need to define data type of variable to use it and you can not assign incompatible data type otherwise the compiler will give you an error. *
Data types *
Primitive data types Data Type Default Value Default size boolean false 1 bit char ‘\u0000’ 2 byte byte 1 byte short 2 byte int 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte *
Reference data types Reference data types are those data types which are provided as class by Java API or by class that you create. String is an example of Reference data types provided by java . String is an object of the class java.lang.String. *
Variables These are used to store the values of elements while the program is executed. Types of variables Local variable A Variable which is declared inside a method can be termed as Local Variable. It is mandatory to initialize local variable otherwise Compiler will complain about it. Instance variable A Variable which is declared at class level can be termed as Instance variable. It is not mandatory to initialize Instance variable. All instance variable will be by default initialized by JVM. Static variable A Variable which is declared as static is known as Static variable. Static variables are class level variables. *
Variables: Variables is an identifier used to store value. Giving values to variables: 1) Assignment statement:- Ex: int a=10; 2) Read statement:- Ex: Scanner sc=new Scanner( System.in ); int a= sc.readInt (); 1001 1002 1003 1004 1005 . . memory 1001 a int a;
Read statement :- giving values to variable interactively through the keyboard using the scanner class methods . Java User Input (Scanner) The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine () method, which is used to read Strings:
nextBoolean () Reads a boolean value from the user nextByte() Reads a byte value from the user nextDouble() Reads a double value from the user nextFloat() Reads a float value from the user nextInt() Reads a int value from the user nextLine() Reads a String value from the user nextLong() Reads a long value from the user nextShort () Reads a short value from the user Input types Method Description
// Write a program on scanner class import java.util.Scanner ; class scanner { public static void main(String args []) { Scanner s1=new Scanner( System.in ); System.out.println (“Enter values=”); int a=s1.nextInt(); int b=s1.nextInt(); int c= a+b ; System.out.println (“result=”+c); } }
Variable Demo Program public class VariableDemo { int a ; // Instance variable static int b = 20 ; // static variable public void prints() { int c = 10 ; // local variable System . out .println( "Method local variable: " + c ); } public static void main( String args []) { //Instance and static variable VariableDemo demo = new VariableDemo(); System . out .println( "Instance variable: " + demo . a ); System . out .println( "Static variable: " + b ); demo .prints(); } } *
import java.util.Scanner ; class demo { public static void main(String[] args ) { Scanner Obj = new Scanner( System.in ); System.out.println ("Enter name, age and salary:"); String name = Obj.nextLine (); int age = Obj.nextInt (); double salary = Obj.nextDouble (); System.out.println ("Name: " + name); System.out.println ("Age: " + age); System.out.println ("Salary: " + salary); } }
readLine () : method belongs to BufferedReader class which is used to reads the input from the keyboard as string which is then converted to the corresponding datatype using wrapper classes. Ex:Integer.parseInt (), Float.parseFloat (), Double.parseDouble (), Character.parseChar ()
import java.io.*; class Example { public static void main(String args []) throws Exception{ InputStreamReader r= new InputStreamReader ( System.in ); BufferedReader br = new BufferedReader (r); System.out.println ("Enter your name"); String name= br.readLine (); System.out.println ("Welcome "+name); } }
Arrays in JAVA Array is collection of related data items Creating an array Declare an array Create memory location Putting values to memory locations
Declaring an Array Variable Do not have to create an array while declaring array variable <type> [ ] variable_name ; Double[ ] myList ; double myList [ ]; Both syntaxes are equivalent No memory allocation at this point
Defining an Array Define an array as follows: variable_name =new <type> [ arraySize ]; Number = new int [5]; Mylist = new int [10 ]; It creates an array using new dataType [ arraySize ]; It assigns the reference of the newly created array to the variable variable_name . dataType arrayname [ ] = {list of values}; Int a [ ]={1,2,3,4,5,6,7,}; Array index starts from 0 to arraySize-1; int is of 4 bytes, total space=4*10=40 bytes Declaring and defining in the same statement: Double [ ] mylist = new double [10];
Creating arrays cntd ...
What happens if we define different type… We define Int [ ] a=new long[20]; incompatible types found: long[] required: int [] The right hand side defines an array, and thus the array variable should refer to the same type of array Example: int prime[100]; error=> ']' expected long primes[20]; The C++ style is not permitted in JAVA syntax long[] primes = new long[20]; primes[25]=33; Runtime Error: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
Array Size through Input …. BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); String inData ; int num ; System.out.println ("Enter a Size for Array:"); inData = stdin.readLine (); num = Integer.parseInt ( inData ); // convert inData to int long[] primes = new long[ num ]; System.out.println (“Array Length=”+ primes.length ); …. SAMPLE RUN: Enter a Size for Array: 4 Array Length=4
Example for array public class TestArray { public static void main(String[] args ) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList ) { System.out.println (element); } } } Otput : 1.9 2.9 3.4 3.5
Reusing Array Variables int [] primes=new int [10]; …… primes=new int [50]; Previous array will be discarded Cannot alter the type of array
Array Length Refer to array length using length() method A data member of array object array_variable_name.length for( int k=0; k< primes.length;k ++) Sample Code: l ong[ ] primes = new long[20]; System.out.println ( primes.length ) ; Output: 20 If number of elements in the array are changed, JAVA will automatically change the length attribute!
Sample Program class MinArray { public static void main ( String[] args ) { int [] array = { 20, 19, 1, 5, 71, 27, 19, 95 } ; int min=array[0]; // initialize the current minimum for ( int index=0; index < array.length ; index++ ) if ( array[ index ] < min ) min = array[ index ] ; System.out.println ("The minimum of this array is: " + min ); } }
Two dimenssional array Representing 2D arrays Int myarray [][]; Myarray = new int [3][4]; Int myarray [][] = new int [3][4]; Example Int myarray [2][3]={0,0,0,1,1,1}; 2 columns and 3 rows
Operators in java Operator in Java is a symbol which is used to perform operations on operands. There are many types of operators in Java which are given below: 1)Arithmetic Operator 2)Relational Operator 3)Logical Operator 4)Assignment Operator. 5)Increment and decrement 6)Conditional 7)Bitwise Operator 8)Special operator
ArithmeticOperator : A rithmatic operators can be used to perform simple mathematical calculations. For example: +, -, *, / etc. . class OperatorExample { public static void main(String args []) { int a=10; int b=5; System.out.println ( a+b ); System.out.println (a-b); System.out.println (a*b); System.out.println (a/b); System.out.println ( a%b ); } }
Relational operators : Relational operators can be used to compare two operands. For Example: < , > , <= , >= , == , != class Relation { public static void main(String args []) { int a=10,b=5; System.out.println (“a<b is“+(a<b)); System.out.println (“a>b is“+(a>b)); System.out.println (“a==b is”+(a==b)); System.out.println (“a<=b is”+(a<=b)); System.out.println (“a>=b is”+(a>=b)); System.out.println (“a!=b is “+(a!=b)); } }
Logical operator: Logical operator can be used to combine two or more conditions into one main condition.Based on this main condition the If-Statement makes decision. For Example: &&(And) , ||(OR) , !(Not) Logical AND’ Operator(&&): This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. Logical OR' Operator(||): This operator returns true when one of the two conditions under consideration are satisfied or are true. If even one of the two yields true, the operator results true. Logical NOT' Operator(!): This is a unary operator returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false.
Logical AND’ Operator(&&): class Logic { public static void main(String args []) { int age=25,experience=3; if((age>22)&&(experience>2)) { System.out.println (“eligible”); } else { System.out.println (“not eligible”); } } }
class Logic { public static void main(String args []) { int age=25,experience=3; if((age>22)||(experience>2)) { System.out.println (“eligible”); } else { System.out.println (“not eligible”); } } } Logical OR' Operator(||):
Logical NOT' Operator(!) class Logical { public static void main(String[] args ) { int a = 10, b = 1; System.out.println ("Var1 = " + a); System.out.println ("Var2 = " + b); System.out.println ("!(a < b) = " + !(a < b)); System.out.println ("!(a > b) = " + !(a > b)); } } Output: Var1 = 10 Var2 = 1 !(a < b) = true !(a > b) = false
Assignment Operator: Assignment operator is one of the most common operator. It is used to assign the value on its right to the operand on its left . For Example: = class Operator { public static void main(String args []) { int a,b ; a=10; b=20; System.out.println (a); System.out.println (b); } }
Increment and Decrement operator: Increment operator increments the value of variable by one which it is operating. For Example: ++ class Increment { public static void main(String args []) { int m=10, n=5; System.out.println (“m=“+m); System.out.println (“n=“+n); System.out.println (“++m=“+(++m)); System.out.println (“m++=“+(m++)); System.out.println (“++n=“+(++n)); System.out.println (“n++=“+(n++)); System.out.println (“m=“+m); System.out.println (“n=“+n); } }
Decrement operator: Decrement operator decrements the value of variable by one which it is operating. For Example: -- class Decrement { public static void main(String args []) { int m=10, n=5; System.out.println (“m=“+m); System.out.println (“n=“+n); System.out.println (“--m=“+(--m)); System.out.println (“m--=“+(m--)); System.out.println (“--n=“+(--n)); System.out.println (“n--=“+(n--)); System.out.println (“m=“+m); System.out.println (“n=“+n); } }
Conditional operator: Conditional operator will verifies the condition if the condition is true then it will considers as the first argument after the (?) and if the condition is false it considers the second argument after( :) symbol. Syntax: (condition)?argument1:argument2;
class Conditional { public static void main(String args []) { int a=10,b=20,x; x=a< b?a:b ; System.out.println (“x=“+x); } }
Bitwise operator: Bitwise operators are used to perform the manipulation of individual bits of a number. It is used to test the bits,or shifting them to the right or left. For Example: &, | , ~ ,^ ,<< , >> class Bitwise { public static void main(String args []) { int a=60, b=13; System.our.println ( a&b ); System.our.println ( a|b ); System.our.println ( a^b ); System.out.println (~a); System.out.println (a<<2); System.out.println (a>>2); } }
Binary AND & Bitwise OR
Binary XOR & Once Complement
Binary Left Shift & Right Shift
Special operator: Java support some special operator such as 1) Dot operator 2) instanceof operator 1)Dot operator: Dot operator is used to access the instance variables & methods of class objects. Ex: person.display (); 2) instanceof operator: The instanceof is an object reference operator & returns true if the object on the lefthand side is an instanceof the class given on the righthand side. Ex: person instanceof student
Bitwise operator: It is used to test the bits,or shifting them to the right or left. For Example: << , >> , ~ class Bitwise { public static void main(String args []) { int a=60; int b=13; System.out.println (a<<2); System.out.println (a>>2); System.out.println (~a); } }
Special operator: Java support some special operator such as 1) Dot operator 2) instanceof operator 1)Dot operator: Dot operator is used to access the instance variables & methods of class objects. Ex: person.display (); 2) instanceof operator: The instanceof is an object reference operator & returns true if the object on the lefthand side is an instanceof the class given on the righthand side. Ex: person instanceof student
class student { int age=30; void display() { System.out.println (age); } } class detail { public static void main(String args []) { student person=new student(); person.display (); } }
Program on instanceof operator class test { public static void main(String args []) { String name=“ james ”; boolean result=name instanceof String; System.out.println (result); } }
TWO OBJECTS class box { int w,h,d ; public int volume() { return w*h*d; }} class demo { public static void main(String args []) { box obj1=new box(); box obj2=new box(); obj1.w=1; obj1.h=2; obj1.d=3; obj2.w=4; obj2.h=5; obj2.d=6; int vol =obj1.volume(); System.out.println ("volume="+ vol ); int vol =obj2.volume(); System.out.println ("volume="+ vol ); }} w h d volume () obj1 w h d volume () obj2
Program that uses a parameterized method class box { int w,h,d ; public int volume( int w,int h,int d) { int vol = w*h*d; System.out.println ("volume="+ vol ); } } class demo { public static void main(String args []) { box obj1=new box(); box obj2=new box(); obj1.volume(1,2,3); obj2.volume(5,6,7); } }
Conditional statements Conditional statements are used to perform different actions based on different conditions. The following conditional statements are: if statement if-else statement if-else-if ladder nested if statement
1)If statement: The Java if statement tests the condition. It executes the if block if condition is true. Syntax: if (condition){ //code to be executed } Ex: class stmt { public static void main(String args []) { int stdmarks =70; if( stdmarks >=60) { System.out.println (“passed”); } } }
class IfExample { public static void main(String[] args ) { int age=20; if (age>18) { System.out.print ("Age is greater than 18"); } } }
2) if-else Statement: The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. Syntax: if (condition){ //code if condition is true } else { //code if condition is false }
//To display result class stmt { public static void main(String args []) { int stdmarks =60; if( stdmarks >=50) { System.out.println (“passed”); } else { System.out.println (“fail”); } } }
//It is a program of odd and even number. class IfElseExample { public static void main(String[] args ) { int number=13; if (number%2==0) { System.out.println ("even number"); } Else { System.out.println ("odd number"); } } }
3)if-else-if ladder Statement: The if-else-if ladder statement executes one condition from multiple statements. Syntax: if (condition1){ //code to be executed if condition1 is true } else if (condition2){ //code to be executed if condition2 is true } else if (condition3){ //code to be executed if condition3 is true } ... else { //code to be executed if all the conditions are false }
Nested if statement: The nested if statement represents the if block within another if block . Here, the inner if block condition executes only when outer if block condition is true. Syntax: if (condition) { //code to be executed if (condition) { //code to be executed } }
//Java Program to demonstrate the use of Nested If Statement class JavaNestedIfExample { public static void main(String[] args ) { int age=20; int weight=80; if (age>=18) { if (weight>50) { System.out.println ("You are eligible to donate blood"); } } } }
Conditional loops In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true. There are three types of loops in Java. for loop while loop do-while loop
1) 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.
A simple for loop is the same as C / C++ . We can initialize the variable , check condition and increment/decrement value. It consists of four parts: Initialization : It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition. Condition : It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition. Statement : The statement of the loop is executed each time until the second condition is false. Increment/Decrement : It increments or decrements the variable value. It is an optional condition. Syntax: for ( initialization;condition;incr / decr ) { //statement or code to be executed }
class ForExample { public static void main(String[] args ) { for ( int i =1;i<=10;i++) { System.out.println ( i ); } } }
Java Nested For Loop If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes. class NestedForExample { public static void main(String[] args ) { for ( int i =1;i<=2;i++) { for ( int j=1;j<=2;j++) { System.out.println ( i +" "+j); } } } }
Output: 11 12 21 22
Java for-each Loop The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. 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 } Example: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println ( i ); } The example above can be read like this: for each String element (called i - as in i ndex) in cars , print out the value of i .
/Java For-each loop example which prints the //elements of the array public class ForEachExample { public static void main(String[] args ) { //Declaring an array int arr []={12,23,44,56,78}; //Printing array using for-each loop for( int i:arr){ System.out.println ( i ); } } }
//Java program to demonstrate the use of infinite for loop which prints an statement public class ForExample { public static void main(String[] args ) { //Using no condition in for loop for (;;) { System.out.println ("infinitive loop"); } } } Output: infinitive loop infinitive loop infinitive loop infinitive loop infinitive loop ctrl+c
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 loop. Syntax: while (condition){ //code to be executed }
public class WhileExample { public static void main(String[] args ) { int i =1; while ( i <=10){ System.out.println ( i ); i ++; } } }
Java Infinitive While Loop If you pass true in the while loop, it will be infinitive while loop. Syntax: while ( true ){ //code to be executed } Example: public class WhileExample2 { public static void main(String[] args ) { while ( true ){ System.out.println ("infinitive while loop"); } } } Output: infinitive while loop infinitive while loop infinitive while loop infinitive while loop infinitive while loop ctrl+c
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. Syntax: do { //code to be executed } while (condition);
public class DoWhileExample { public static void main(String[] args ) { int i =1; do { System.out.println ( i ); i ++; } while ( i <=10); } }
Java Infinitive do-while Loop If you pass true in the do-while loop, it will be infinitive do-while loop. Syntax: do { //code to be executed } while ( true ); Example: public class DoWhileExample2 { public static void main(String[] args ) { do { System.out.println ("infinitive do while loop"); } while ( true ); } }
Java Switch Statement The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int , long, enum types, String and some wrapper types like Byte, Short, Int , and Long. Since Java 7, you can use strings in the switch statement. In other words, the switch statement tests the equality of a variable against multiple values. Points to Remember There can be one or N number of case values for a switch expression. The case value must be of switch expression type only. The case value must be literal or constant . It doesn't allow variables. The case values must be unique . In case of duplicate value, it renders compile-time error. The Java switch expression must be of byte, short, int , long (with its Wrapper type), enums and string . Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case. The case value can have a default label which is optional.
Syntax: 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; }
class SwitchExample { public static void main(String[] args ) { //Declaring a variable for switch expression int number=20; //Switch expression switch (number){ //Case statements case 10: System.out.println ("10"); break ; case 20: System.out.println ("20"); break ; case 30: System.out.println ("30"); break ; //Default case statement default :System.out.println (“Not in 10, 20 or 30 "); } } }
class SwitchExample { public static void main(String[] args ) { int i ; for( i =1;i<=4;i++) { switch ( i ) { Case 1:c= a+b ; System.out.println (c); break; Case 2:c=a-b; System.out.println (c); break; Case 3:c=a*b; System.out.println (c); break; Case 4:c=a/b; System.out.println (c); break; default :System.out.println (" no operation "); } } }
Break and continue: The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break statement in all types of loops such as for loop, while loop and do-while loop. The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
class MyClass { public static void main(String[] args ) { for ( int i = 0; i < 10; i ++) { if ( i == 4) { break; } System.out.println ( i ); } } }
class MyClass { public static void main(String[] args ) { for ( int i = 0; i < 10; i ++) { if ( i == 4) { continue; } System.out.println ( i ); } } }
Pyramid Example 1: public class PyramidExample { public static void main(String[] args ) { for ( int i =1;i<=5;i++) { for ( int j=1;j<= i;j ++) { System.out.print ("* "); } System.out.println ();//new line } } }
Pyramid Example 2: public class PyramidExample2 { public static void main(String[] args ) { int term=6; for ( int i =1;i<= term;i ++) { for ( int j= term;j >= i;j --) { System.out.print ("* "); } System.out.println ();//new line } } }
Java Labeled For Loop We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can break/continue specific for loop. Usually, break and continue keywords breaks/continues the innermost for loop only. Syntax: labelname : for( initialization;condition;incr / decr ) { //code to be executed }
//A Java program to demonstrate the use of labeled for loop public class LabeledForExample { public static void main(String[] args ) { //Using Label for outer and for loop aa : for ( int i =1;i<=3;i++){ bb: for ( int j=1;j<=3;j++){ if ( i ==2&&j==2){ break aa ; } System.out.println ( i +" "+j); } } } }
Output: 1 1 1 2 1 3 2 1 If you use break bb; , it will break inner loop only which is the default behavior of any loop.
public class LabeledForExample2 { public static void main(String[] args ) { aa : for ( int i =1;i<=3;i++){ bb: for ( int j=1;j<=3;j++){ if ( i ==2&&j==2){ break bb; } System.out.println ( i +" "+j); } } } }
Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3
Type conversion or Type casting Conversion from one data type value to another data type value is known as type conversion. Java supports type conversion in two ways. 1)Implicit conversion 2)Explicit conversion Implicit convertion: converting from one datatype value to another datatype value internally is called implicit convertion . It convert provided the following two condition are satisfied
Destination and source variable type should be type compatible( i.e the datatypes of variables should belong to same datatype category ) The destination variable data type size is larger than source variable datatype .
Implicit conversion Ex: int x; short y=20; x=y;//correct Ex: int x=30; short y; y=x;//error Type size byte 1 byte short 2 byte int 4 byte long 8 byte
Program on Implicit conversion public class Conversion{ public static void main(String[] args ) { int i = 200; //automatic type conversion long l = i ; //automatic type conversion float f = l; System.out.println (" Int value "+ i ); System.out.println ("Long value "+l); System.out.println ("Float value "+f); } } Int value 200 Long value 200 Float value 200.0 Output
Explicit convertion : converting the source datatype value to the destination datatype explicitly is known as explicit type convertion Ex: int x=300; byte y; y=(byte)x; Ex: int x; float y=95.67; x=( int )y;
Explicit conversion class Narrowing { public static void main(String[] args ) { double d = 200.06; long l = (long)d; //explicit type casting int i = ( int )l; //explicit type casting System.out.println ("Double Data type value "+d); System.out.println ("Long Data type value "+l); //fractional part lost System.out.println (" Int Data type value "+ i ); //fractional part lost } } Double Data type value 200.06 Long Data type value 200 Int Data type value 200 output
Arrays in java Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. To declare an array, define the variable type with square brackets : Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Types of Array in java There are two types of array. Single Dimensional Array Multidimensional Array
Single Dimensional Array A list of items can be given one variable name using only one subscript & such a variable is called one dimensional array. Syntax to Declare an Array in Java datatype arrayname []; Ex: int n[]; Instantiation of an Array in Java array_name = new datatype [size]; Ex: n=new int [5]; arrayname [subscript]=value; Ex: n [0]=35;
class Testarray { public static void main(String args []) { int a[]= new int [5]; //declaration and instantiation a[0]=10; //initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for ( int i =0;i< a.length;i ++)//length is the property of array System.out.println (a[ i ]); } } 10 20 70 40 50 0 1 2 3 4
Multidimensional Array in Java In such case, data is stored in row and column based index (also known as matrix form). Two dimensional arrays are similar to single dimensional arrays,the only difference is a two dimensional array has two dimensions. Syntax to Declare Multidimensional Array in Java arrayname =new datatype [no. Of Elements] [no. Of Elements] (OR) datatype arrayname [][]={ {value1,values2…….}, {value3,values4……} }; Example to instantiate Multidimensional Array in Java a=new int [2][3];
Example of Multidimensional Java Array class Testarray3 { public static void main(String args []) { //declaring and initializing 2D array int arr [][]={{10,20,30},{40,50,60}}; //printing 2D array for ( int i =0;i<2;i++) { for ( int j=0;j<3;j++) { System.out.print ( arr [ i ][ j]+“\t "); } System.out.print (“\n”); } } } 10 20 30 40 50 60 Output :
For-each Loop for Java Array We can also print the Java array using for-each loop . The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop. class Testarray1 { public static void main(String args []){ int arr []={33,3,4,5}; //printing array using for-each loop for ( int i:arr) System.out.println ( i ); } } The syntax of the for-each loop is given below: for ( data_type variable:array ){ //body of the loop }
Passing Array to a Method in Java We can pass the java array to method so that we can reuse the same logic on any array. class Testarray2 { //creating a method which receives an array as a parameter static void min( int arr []) { int min= arr [0]; for ( int i =1;i< arr.length;i ++) if (min> arr [ i ]) min= arr [ i ]; System.out.println (min); } public static void main(String args []) { int a[]={33,3,4,5};// declaring and initializing an array min(a);// passing array to method } } 3 output
Anonymous Array in Java Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method. //Java Program to demonstrate the way of passing an anonymous array //to method . class TestAnonymousArray { //creating a method which receives an array as a parameter static void printArray ( int arr []) { for ( int i =0;i< arr.length;i ++) System.out.println ( arr [ i ]); } public static void main(String args []) { printArray ( new int []{10,22,44,66});/ /passing anonymous array to method } }
Output: 10 22 44 66
Returning Array from the Method We can also return an array from the method in Java. //Java Program to return an array from the method class TestReturnArray { //creating method which returns an array static int [] get() { return new int []{10,30,50,90,60}; } public static void main(String args []) { //calling method which returns an array int arr []=get(); //printing the values of an array for ( int i =0;i< arr.length;i ++) System.out.println ( arr [ i ]); } }
Output: 10 30 50 90 60
Multidimensional Array in Java In such case, data is stored in row and column based index (also known as matrix form). Two dimensional arrays are similar to single dimensional arrays,the only difference is a two dimensional array has two dimensions. Syntax to Declare Multidimensional Array in Java arrayname =new datatype [no. Of Elements] [no. Of Elements] (OR) datatype arrayname [][]={ {value1,values2…….}, {value3,values4……} }; Example to instantiate Multidimensional Array in Java a=new int [2][3];
Example of Multidimensional Java Array class Testarray3 { public static void main(String args []) { //declaring and initializing 2D array int arr [][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for ( int i =0;i<3;i++) { for ( int j=0;j<3;j++) { System.out.print ( arr [ i ][j]+" "); } System.out.println (); } } } 1 2 3 2 4 5 4 4 5 Output :
Jagged Array : If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is an array of arrays with different number of columns class Main { public static void main(String[] args ) { int arr [][] = new int [2][]; // Declaring 2-D array with 2 rows arr [0] = new int [3]; // First row has 3 columns arr [1] = new int [2]; // Second row has 2 columns int count = 0; for ( int i =0; i < arr.length ; i ++) // Initializing array for( int j=0; j< arr [ i ].length; j++) arr [ i ][j] = count++; System.out.println ("Contents of 2D Jagged Array"); for ( int i =0; i < arr.length ; i ++) // Displaying the values of 2D Jagged array { for ( int j=0; j< arr [ i ].length; j++) System.out.print ( arr [ i ][j] + " "); System.out.println (); } } } 0 1 2 3 4 Output:
Addition of 2 Matrices in Java class Testarray5 { public static void main(String args []){ //creating two matrices int a[][]={{1,3,4},{3,4,5}}; int b[][]={{1,3,4},{3,4,5}}; /creating another matrix to store the sum of two matrics int c[][]= new int [2][3]; //adding and printing addition of 2 matrices for ( int i =0;i<2;i++){ for ( int j=0;j<3;j++){ c[ i ][j]=a[ i ][j]+b[ i ][j]; System.out.print (c[ i ][j]+" "); } System.out.println ();//new line } }} Output: 2 6 8 6 8 10
// This a first java program class sample { public static void main(String args []) { System.out.println (“welcome to java lab”); } }
// Write a java program to add two numbers . class add { public static void main(String args []) { int a,b,c ; a=100; b=200; c= a+b ; System.out.println (“result=“+c); } }
// Write a java to print biggest of two numbers . class big { public static void main(String args []) { int a,b ; a=100; b=200; if(a>b) System.out.println (“biggest=“+a); else System.out.println (“biggest=“+b); } }
// Write a java to print 1 to 10 numbers . class loop { public static void main(String args []) { int i ; for( i =1;i<=10;i++) { System.out.println (“number=“+ i ); } } }
public static void main(String args []) public: public keyword is an acess specifier which allows the programmer to control the visibility of class members. static: The keyword static allows main() to be called without having to instantiate a particular instance of the class. void: It tells the compiler that main() does not have return type. main(): Every java program execution starts from main function. String args []: Declares a parameter named args which is an array of instances of the class string.
//With static method. class A { public static void show() { System.out.println (“welcome”); } } class B { public static void main(String args []) { A.show (); } } With out static method class A { public void show() { System.out.println (“welcome”); } } class B { public static void main(String args []) { A obj =new A(); obj.show (); } } gedit A.java javac A.java Java B
Returning a value class box { int w,h,d ; public int volume() { return w*h*d; } } class demo { public static void main(String args []) { box obj =new box(); obj.w =1; obj.h =2; obj.d =3; int vol = obj.volume (); System.out.println ("volume="+ vol ); } }
Example: Argument,parameter,signature class sample { int x; public void display( int a) { x=a; System.out.println (x); } } class ex { public static void main(String args []) { sample obj =new sample(); obj.display (20); } }
Command Line argument: It is also possible to pass values to main() method & it can be passed from command line because main() method is known as command line arguments(run time) Values passed from command line exist in the form of strings therefore the argument in the main() is Strings therefore the argument in the main() is defined as an array of String type.
Program to concatenate two argument value. class commandline { public static void main(String args []) { String c= args [0]+ args [1]; System.out.println (“result=“+c); } }
// Program on command line argument . class commandline { public static void main(String args []) { int a,b,c ; a= Integer.parseInt ( args [0]); b= Integer.parseInt ( args [1]); c= a+b ; System.out.println (“result=“+c); } } 100 200 1 args
System.out.print (): class System { public PrintStream out; . . . } class PrintStream { . public void print(); public void print( int ); public void print(double); public void print(char); public void print( boolean ); public void print(float); public void println (); public void println ( int ); public void println (char); public void println (float); public void println ( boolean ); public void println (double); public void println ( java.lang.string ); public void println ( java.lang.object ); . }
Scope and lifetime of a variable: Scope determines the life time and visibility of an Identifier. Identifier such as the variable name ,function name can be used only in certain areas of a a program.
class test { public static void main(String args []) { int x=10; if(x==10) { int y=20; System.out.println (“x=“+x); System.out.println (“y=“+y); x=y*2; } System.out.println (“x=“+x ); // System.out.println (“y=“+y); } }
Access specifier The access specifier of a members specifies the scope of the member where it can be accessed. There are four types: 1)Default: 2)Public: 3)Private: 4)Protected Syntax: class classname { access_specifier type instance_variable =value; ………. access_specifier returntype methodname ([type para1,…]) { //body of method } }
2)Public: Ex: class A { public int x=10; } 3)Private: Ex: class A { private int x=10; } 4)Protected: Ex: class A { protected int x=10; } 1)Default: Ex: class A { int x=10; }
Default :the default member can be accessed inside and outside the class but in the same package. Public :the acess level of public modifier can be accessed within the class outside the class with in the package,outside the package. Private: the members declared with the access Specifier private can be accessed only with in the class. Protected: the member declared with the access specifier protected can be accessed with in the Class as well as its subclass.
structure str { int roll_no ; char name[20]; }; C Structure C++ Structure structure str { int roll_no ; char name[20]; member function(); };
Ex:int a=10; Ex:int a[3]; a[0]=10; a[1]=20; a[2]=30; structure str { char name[20]; int id; }; str name id
class sample { public int a=10; private int b=20; protected int c=30; int d=40; public static void main(String args []) { sample obj =new sample(); System.out.println ( obj.a ); System.out.println ( obj.b ); System.out.println ( obj.c ); System.out.println ( obj.d ); } }
Write a program by using public , private,protected class Sample { private int x=10; public int y=20; protected int z=30; int p=40; } class ex1 { public static void main(String args []) { Sample obj =new Sample(); // System.out.println ( obj.x ); System.out.println ( obj.y ); System.out.println ( obj.z ); System.out.println ( obj.p ); } }
class A { private int x=10; public int y=20; protected int z=30; int p=40; } class B extends A { void display() { // System.out.println (x); System.out.println (y); System.out.println (z); System.out.println (p); } } class C extends B { void show() { // System.out.println (x); System.out.println (y); // System.out.println (z); System.out.println (p); } } class example { public static void main(String args []) { C obj =new C(); B obj2=new B(); obj2.display(); obj.show (); } }
Accessing private variable in class To access or work with private instance of class we have to define public method in the class. Ex:we create a class with one private variable x and we would like to perform two operations on this variable. 1)setting value to x 2)printing value of x
Accessing private variable in class class sample { private int x; public void set( int a) { x=a; } public void display() { System.out.println (“x=“+x); } } class ex { public static void main(String args []) { sample obj =new sample(); obj.set (100); obj.display (); }}