Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

UNIT1-JAVA.pptx

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Nächste SlideShare
OOPJ.pptx
OOPJ.pptx
Wird geladen in …3
×

Hier ansehen

1 von 191 Anzeige

Weitere Verwandte Inhalte

Ähnlich wie UNIT1-JAVA.pptx (20)

Anzeige

Aktuellste (20)

UNIT1-JAVA.pptx

  1. 1. UNIT-I Programming Paradigms: Procedural Programming, Modular Programming, Object Oriented Programming and Generic Programming, Object Oriented Programming Concepts. Java basics: Creation of Java, Java buzzwords, Data types, Variables and Arrays, Operators, Control statements, introductions to classes and simple programs.
  2. 2. 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.
  3. 3. 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. *
  4. 4. 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. *
  5. 5. 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
  6. 6. 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.
  7. 7. 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.
  8. 8. 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.
  9. 9. 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.
  10. 10. 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 :
  11. 11. 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.
  12. 12. 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>;
  13. 13. 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.
  14. 14. 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); } }
  15. 15. 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.
  16. 16. Features/Buzzwords of java: Features /Buzzwords of java 1)Compiled and Interpreted 2)Platform independent 3)Object oriented 4)Robust 5)Secure 6)Garbage Collector 7)Distributed 8)Simple 9)Multi threaded
  17. 17. Compiled and Interpreted Java uses compiler and interpreter both. Java source code is converted into byte code at compilation time. The interpreter executes this byte code at runtime and produces output. Java is interpreted that is why it is platform independent. Source code Byte Code Java Virtual Machine Host System
  18. 18. Platform Independent Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs. Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into byte 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).
  19. 19. Object oriented Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior.
  20. 20. Robust Robust simply means strong. Java is robust because: It uses strong memory management. There is a 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 are exception handling and the type checking mechanism in Java. All these points make Java robust.
  21. 21. Secure Java programs are secured programs because web applets of java executes only in browsers and cannot acess any resources of computer such as files on hard disk,data in RAM etc.. Virus programs do not enter into computer through web applets.
  22. 22. Garbage Collector Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
  23. 23. Distributed Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  24. 24. Simple Java is very easy to learn, and its syntax is simple, clear and easy to understand. According to Sun, Java language is a simple programming language because: Java syntax is based on C++ (so easier for programmers to learn it after C++). Java has removed many complicated and rarely- used features, for example, explicit pointers, operator overloading, etc.
  25. 25. 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.. Threads are important for multi-media, Web applications, etc.
  26. 26. Types of java Applications • Web Application • Stand alone Application • Enterprise Application • Mobile Application Desk/window/console Web application Mobile Application J2SE J2EE J2ME JAVA
  27. 27. OOP Concept 1)Class 2)Object 3)Data Abstraction 4)Encapsulation 5)Inheritance 6)polymorphism 7)Dynamic Binding 8)Message passing
  28. 28. 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 } ………… }
  29. 29. Example: Class Studentdetails { public int roll_no; protected String name; void display() { System.out.println(name); System.out.println(roll_no); } }
  30. 30. 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
  31. 31. 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();
  32. 32. • 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.
  33. 33. 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();
  34. 34. 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(); } } name roll_no display () obj memory 1001 1001 Reference Variable Object
  35. 35. 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.
  36. 36. Example 1)In pop, program is divided into small parts called function . 1)In oop, program is divided into small parts called object.
  37. 37. 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.
  38. 38. 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); } }
  39. 39. 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); } }
  40. 40. structure str { int roll_no; char name[20]; }; C Structure C++ Structure structure str { int roll_no; char name[20]; member function(); };
  41. 41. 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
  42. 42. 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.
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. 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
  47. 47. Example: class A { int x=10; } class B extends A { System.out.println(x); } x=10
  48. 48. 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: void area(int s) { System.out.println(s); } void area(int l,int b) { System.out.println(l*b); }
  49. 49. 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. class A { void sum(int x,int y) { System.out.println(x+y); } } class B { public static void main(String args[]) { A obj=new A(); obj.sum(2,4); } } Dynamic binding
  50. 50. 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
  51. 51. Example Different between pop and oop 1)In pop, program is divided into small parts called function . 1)In oop, program is divided into small parts called function.
  52. 52. 2) In C the data is not secured. 3) Does not have any Access specifier. 4) To add new data and function is not so easy. 5) Pop follows Top-down approach. 6) C programming file is saved with( .c) extension. Ex: gedit filename.c 2) In oop the data is secured. 3) oop has Access specifier named public,private,protected. 4)provides an easy way to add new data and function . 5) oop follows Bottom –up approach. 6) Java programming file is saved with( .java) extension. Ex: gedit filename.java
  53. 53. Name - Praneetha Roll_no - 17641A0541 Course - CSE Fee - 90,000 void main() { char name[30]; int roll_no; char course[30]; int fee; //other code operations } POP OOP char name[30]; int roll_no; char course[30]; int fee; function display details(); class object1; class object2; void main() class student Example – Object Oriented Programming in Real World
  54. 54. Benefits of OOP • Through inheritance we can eliminate redundant and extend the use of existing classes. • The principle of data hiding helps the programmer build secure programs. • It is easy to partition the work in a project based on objects.
  55. 55. class Box { double width,height,depth; } class demo { public static void main(String args[]) { Box obj=new Box(); double vol; obj.width=10; obj.height=20; obj.depth=30; vol=obj.width*obj.height*obj.depth; System.out.println(“volume is “+vol); }}
  56. 56. 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
  57. 57. Program that uses a parameterized method class box { int w,h,d; public int volume(int w,int h,int d) { return w*h*d; } } class demo { public static void main(String args[]) { box obj1=new box(); box obj2=new box(); int a=obj1.volume(1,2,3); System.out.println("volume="+a); int b=obj2.volume(5,6,7); System.out.println("volume="+b); }}
  58. 58. 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. *
  59. 59. Data types *
  60. 60. Primitive data types Data Type Default Value Default size boolean false 1 bit char ‘u0000’ 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte *
  61. 61. 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. *
  62. 62. Variables: These are used to store the values of elements while the program is executed. 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;
  63. 63. 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:
  64. 64. 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
  65. 65. //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); } }
  66. 66. 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); } }
  67. 67. 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()
  68. 68. 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); } }
  69. 69. Types of variable in java 1)Local variables:A variable that is declared with in the method that is called local variable. 2)Instance variables:A variable that is declared with in the class but not in the method is called instance variable. 3)static variables:A variable that is declared with static keyword is called static variable.
  70. 70. Types of variable in java Ex: class A { int amount=100;//instance variable static int pin=2315; void method() { Int age=35;//local variable }
  71. 71. 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();
  72. 72. Documentation section Package statement Import Statement Interface Statement Class Definitions Main method class { Main method definition } Creation of Java / Structure of java Program
  73. 73. 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.
  74. 74. • 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. •
  75. 75. //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); } }
  76. 76. Procedure for implementing java program Creating the program:We can create program using any text editor(note pad). Compile the program: We must compile the java program by javac compiler. Ex:javac sum.java Running the program:java program can be executed by using the interpreter. Ex: java sum
  77. 77. //This a first java program class sample { public static void main(String args[]) { System.out.println(“welcome to java lab”); } }
  78. 78. //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); } }
  79. 79. //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); } }
  80. 80. //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); } } }
  81. 81. 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.
  82. 82. //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
  83. 83. 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); } }
  84. 84. 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); } }
  85. 85. 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.
  86. 86. 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); } }
  87. 87. //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 0 1 args
  88. 88. 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); . }
  89. 89. 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.
  90. 90. 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); } }
  91. 91. 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 } }
  92. 92. 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; }
  93. 93. • 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.
  94. 94. structure str { int roll_no; char name[20]; }; C Structure C++ Structure structure str { int roll_no; char name[20]; member function(); };
  95. 95. 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
  96. 96. 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); } }
  97. 97. 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); } }
  98. 98. 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(); }
  99. 99. 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
  100. 100. 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(); }}
  101. 101. 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
  102. 102. ArithmeticOperator: Arithmatic 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); } }
  103. 103. 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)); } }
  104. 104. 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.
  105. 105. 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”); } } }
  106. 106. 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(||):
  107. 107. 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
  108. 108. 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); } }
  109. 109. 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); } }
  110. 110. 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); } }
  111. 111. 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;
  112. 112. class Conditional { public static void main(String args[]) { int a=10,b=20,x; x=a<b?a:b; System.out.println(“x=“+x); } }
  113. 113. 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); } }
  114. 114. Binary AND & Bitwise OR
  115. 115. Binary XOR & Once Complement
  116. 116. Binary Left Shift & Right Shift
  117. 117. 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
  118. 118. 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); } }
  119. 119. 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
  120. 120. 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(); } }
  121. 121. Program on instanceof operator class test { public static void main(String args[]) { String name=“james”; boolean result=name instanceof String; System.out.println(result); } }
  122. 122. 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
  123. 123. 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); } }
  124. 124. 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
  125. 125. 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”); } } }
  126. 126. class IfExample { public static void main(String[] args) { int age=20; if(age>18) { System.out.print("Age is greater than 18"); } } }
  127. 127. 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 }
  128. 128. //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”); } } }
  129. 129. //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"); } } }
  130. 130. 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 }
  131. 131. class stmt { public static void main(String args[]) { int stdmarks=98; if(stdmarks>=90) System.out.println(“Grade A”); elseif(stdmarks>=80) System.out.println(“Grade B”); elseif(stdmarks>=70) System.out.println(“Grade C”); elseif(stdmarks>=60) System.out.println(“Grade D”); else System.out.println(“failed”); } }
  132. 132. 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 } }
  133. 133. //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"); } } } }
  134. 134. 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
  135. 135. 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.
  136. 136. 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 }
  137. 137. class ForExample { public static void main(String[] args) { for(int i=1;i<=10;i++) { System.out.println(i); } } }
  138. 138. 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); } } } }
  139. 139. • Output: • 11 • 12 • 21 • 22
  140. 140. 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 index) in cars, print out the value of i.
  141. 141. /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); } } }
  142. 142. //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
  143. 143. 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 }
  144. 144. public class WhileExample { public static void main(String[] args) { int i=1; while(i<=10){ System.out.println(i); i++; } } }
  145. 145. 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
  146. 146. 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);
  147. 147. public class DoWhileExample { public static void main(String[] args) { int i=1; do{ System.out.println(i); i++; }while(i<=10); } }
  148. 148. 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); } }
  149. 149. 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.
  150. 150. 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; }
  151. 151. 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 "); } } }
  152. 152. 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 "); } } }
  153. 153. 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.
  154. 154. class MyClass { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 4) { break; } System.out.println(i); } } }
  155. 155. class MyClass { public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 4) { continue; } System.out.println(i); } } }
  156. 156. 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 } } }
  157. 157. 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 } } }
  158. 158. 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 }
  159. 159. //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); } } } }
  160. 160. 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.
  161. 161. 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); } } } }
  162. 162. Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3
  163. 163. 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
  164. 164. • 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.
  165. 165. 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
  166. 166. 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); } } Output: Int value 200 Long value 200 Float value 200.0 Output
  167. 167. 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;
  168. 168. 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
  169. 169. 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.
  170. 170. Types of Array in java There are two types of array. • Single Dimensional Array • Multidimensional Array
  171. 171. • 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;
  172. 172. 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
  173. 173. 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];
  174. 174. 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:
  175. 175. 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 }
  176. 176. 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
  177. 177. 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 } }
  178. 178. Output: 10 22 44 66
  179. 179. 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]); }
  180. 180. Output: 10 30 50 90 60
  181. 181. 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];
  182. 182. 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:
  183. 183. 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:
  184. 184. 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
  185. 185. import java.util.Scanner; public class JavaProgramAddTwoNumber { public static void main(String[] args) { int num1, num2, sum; try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter First Number: "); num1 = sc.nextInt(); System.out.println("Enter Second Number: "); num2 = sc.nextInt(); sum = num1 + num2; System.out.println("Sum of these numbers: " + sum); } } } Addition of Two Numbers OUTPUUT: Enter First Number: 10 Enter Second Number: 20 Sum of these numbers: 30
  186. 186. Java Program to check Even or Odd number public class JavaProgramEvenOddNumber { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { // Read number from user System.out.println("Enter Number: "); int number = sc.nextInt(); /* * If number is divisible by 2 then it's an even number else odd number */ if (number % 2 == 0) { System.out.println("The number " + number + " is even"); } else { System.out.println("The number " + number + " is odd"); } } } } OUTPUT: Enter Number: 10 The number 10 is even
  187. 187. import java.util.Scanner; class AreaOfCircle { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the radius:"); double r= s.nextDouble(); double area=(22*r*r)/7 ; System.out.println("Area of Circle is: " + area); } } 1 2 3 Enter the radius : 7 Area of circle : 154.0 Find Area of Circle

×