Advanced Java Programming - Unit 1

Document Details

SafeTajMahal688

Uploaded by SafeTajMahal688

Tags

java programming java concepts programming languages computer science

Summary

This document provides an introduction to advanced Java programming, detailing the core concepts and components of Java, such as JVM, JRE, and JDK. It also explains the characteristics of the programming language.

Full Transcript

# Advanced Java Programming ## Unit-1 ### Programming in Java #### Introduction Java is a general-purpose, object-oriented, high-level programming language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Java is used to develop Mobile apps, Web apps...

# Advanced Java Programming ## Unit-1 ### Programming in Java #### Introduction Java is a general-purpose, object-oriented, high-level programming language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Java is used to develop Mobile apps, Web apps, Desktop apps, Games and much more. #### Java Architecture Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of interpretation and compilation. It defines all the processes involved in creating a Java program. Java Architecture explains each and every step of how a program is compiled and executed. The below-mentioned points and diagram will simply illustrate Java architecture: 1. There is a compilation and interpretation process in Java. 2. After the JAVA code is written, the JAVA compiler comes into the picture that converts this code into byte code that can be understood by the machine. 3. After the creation of bytecode JAVA virtual machine (JVM) converts it to the machine code, i.e. (.class file) 4. And finally, the machine runs that machine code. * **Source Code** * **Java Compiler** * **Byte Code** * **Java Virtual Machine (JVM)** * **Operating System (OS)** #### Components of Java Architecture * **JVM (Java Virtual Machine)**: The main feature of Java is _Write Once Run Anywhere_. The feature states that we can write our code once and use it anywhere or on any operating system. Our Java program can run any of the platforms only because of the Java Virtual Machine. It is a Java platform component that gives us an environment to execute java programs. JVM's main task is to convert byte code into machine code. * **Java Runtime Environment (JRE)**: It provides an environment in which Java programs are executed. JRE takes our Java code, integrates it with the required libraries, and then starts the JVM to execute it. The JRE contains libraries and software needed by your Java programs to run. * **Java Development Kit (JDK)**: JDK is a software development environment used to develop Java applications and applets. It contains JRE and several development tools: an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) accompanied with another tool. ## Java Buzzwords / Features of Java The Java programming language is a high-level language that can be characterized by all of the following buzzwords: * **Simple**: Java programming language is very simple and easy to learn, understand, and code. Most of the syntaxes in java follow basic programming language C and object-oriented programming concepts are similar to C++. In a java programming language, many complicated features like pointers, operator overloading, structures, unions, etc. have been removed. * **Secure**: Java is said to be more secure programming language because it does not have pointers concept, java provides a feature "applet" which can be embedded into a web application. The applet in java does not allow access to other parts of the computer, which keeps away from harmful programs like viruses and unauthorized access. * **Portable**: Portability is one of the core features of java that enables the java programs to run on any computer or operating system. For example, an applet developed using java runs on a wide variety of CPUs, operating systems, and browsers connected to the Internet. * **Object-oriented**: Java is a pure object-oriented language, almost everything in java is an object, all program code and data reside within object and classes that is everything in java is defined within a class. * **Robust**: Java is more robust because the java code can be executed on a variety of environments, java has a strong memory management mechanism (garbage collector), java is a strictly typed language, it has a strong set of exception handling mechanism, and many more. * **Architecture Neutral**: Java language and Java Virtual Machine (JVM) helped in achieving the goal of "write once; run anywhere, any time, forever". Changes and upgrades in operating systems, processors and system resources will not force any changes in Java Programs. * **Multithreaded**: Java supports multi-threading programming that allows to write programs to do several works simultaneously. A thread is an individual process to execute a group of statements. JVM utilizes multiple threads to execute different blocks of code. Creating multiple threads is called 'multithreaded' in Java. * **Interpreted**: During compilation, Java compiler converts the source code of the program into byte code. This byte code can be executed on any system machine with the help of Java interpreter in JVM. * **High performance**: Java performance is high because of the use of bytecode. The bytecode was used so that it was easily translated into native machine code. * **Distributed**: Java programming language supports TCP/IP protocols which enable the java to support the distributed environment of the Internet. Java also supports Remote Method Invocation (RMI), this feature enables a program to invoke methods across a network. * **Dynamic**: Java programs access various runtime libraries and information inside the compiled code (Bytecode). This dynamic feature allows to update the pieces of libraries without affecting the code using it. ## Path and ClassPath Variables #### Path Once we installed Java on our machine, it is required to Set the PATH environment variable to conveniently run the executable (javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to type the full path of the command, such as: ``` C:\javac TestClass.java ``` Otherwise, you need to specify the full path every time you run it, such as: ``` C:\Java\jdk1.7.0\bin\javac TestClass.java ``` #### Class Path ClassPath is the system environment variable used by the Java compiler and JVM. Java compiler and JVM use Classpath to determine the location of required class files. It contains a path of the classes provided by JDK. ``` C:\Program Files\Java\jdk1.6.0\bin ``` ## Sample Java Program Let's create the Hello World program: ```java class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } ``` In our Hello World program, we have a class called HelloWorld. As a convention, always start the name of your classes with an uppercase letter. To create a class, you use the class keyword, followed by the name of the class. * Every Java program must have a main method. This tells the Java compiler that this is the beginning of the Java program. The program then executes all the statements following the main method. Here's what the main method looks like: ```java public static void main(String[] args) { } ``` * System.out.println() is used to print the statement. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class. ## Compiling and Running Java Programs 1. Write a program on the notepad and save it with .java (for example, DemoProg.java) extension. ```java class DemoProg{ public static void main(String args[]){ System.out.println("Hello!"); System.out.println("Jayanta"); } } ``` 1. Open a command prompt window and go to the directory where you saved the class. Assume it's C:\\demo 2. Type 'javac DemoProg.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line. 3. Now, type 'java DemoProg.java' to run your program. ## Output Methods print() and println() * The println("...") method prints the string "..." and moves the cursor to a new line. * The print("... ") method instead prints just the string "...", but does not move the cursor to a new line. Hence, subsequent printing instructions will print on the same line. * The println() method can also be used without parameters, to position the cursor on the next line. **Example** ```java public class JavaExample { public static void Main(String[] args) { System.out.println("Welcome to Collegenote!"); System.out.println("Welcome to Collegenote!"); System.out.print("Collegenote"); System.out.print("Collegenote"); } } ``` **Output** Welcome to Collegenote! Welcome to Collegenote! CollegenoteCollegenote ## Reading Data Input from Users Java Scanner class allows the user to take input from the console. It belongs to java.util package. **Syntax:** Scanner sc = new Scanner(System.in); **Example** ```java // AddTwoNumbers.java: This program read two numbers from user and finds their sum. import java.util.Scanner; public class AddTwoNumbers { public static void main(String[] args) { int num1, num2, sum; 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); } } ``` ## Arrays in Java Java array is a collection of similar type of elements that have contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. Array in java is index based, for n - sized array first element of the array is stored at 0 index and last element is stored in index n-1. | Element | First index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Indices | | ---------- | ----------- | - | - | - | - | - | - | - | - | - | - | -------- | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Array length is 10 | | | | | | | | | | | | There are two types of array: One-Dimensional Array & Multi-Dimensional Array #### One-Dimensional Arrays In one-dimensional arrays, a list of items can be given one variable name using only one subscript. **Syntax to Declare an Array in Java** `data-type arrayName[];` OR `data-type arrayName;` **For example:** int[] nums; Here, nums is an array that can hold values of type int. **Creation:** When an array is declared, only a reference of an array is created. After declaring an array, we need to create it in the physical memory. Java allows us to create arrays using new operator only, as shown below: `arrayName = new type[size]` **Example:** `int[] nums;` // declare an array `nums = new int[10];` // allocate memory OR `int[] nums = new int[10];` // combining both statements in one **Initialization:** In Java, we can initialize arrays during declaration. For example, `int[] age = {12, 4, 5, 2, 5};` //declare and initialize an array We can also initialize arrays in Java, using the index number. For example, `// declare an array` `int[] age = new int[5];` `// initialize array` `age[0] = 12;` `age[1] = 4;` `age[2] = 5;` **Accessing Array Elements**: We can access the element of an array using the index number. Here is the syntax for accessing elements of an array, **Example:** `array[index]` ```java class Main { public static void main(String[] args) { // create an array int[] age = {12, 4, 5, 2, 5}; // access each array elements System.out.println("Accessing Elements of Array:"); System.out.println("First Element: " + age[0]); System.out.println("Second Element: " + age[1]); System.out.println("Third Element: " + age[2]); System.out.println("Fourth Element: " + age[3]); System.out.println("Fifth Element: " + age[4]); } } ``` #### Q. Write a Java program to find the sum and average of all elements in an array. **Solution:** ```java //Sum_Average.java import java.util.Scanner; public class Sum_Average { public static void main(String[] args) { int n, sum = 0; float average; Scanner s = new Scanner(System.in); System.out.print("Enter no. of elements you want in array:"); n = s.nextInt(); int a[] = new int[n]; System.out.println("Enter all the elements:"); for (int i = 0; i < n; i++) { a[i] = s.nextInt(); sum = sum + a[i]; } System.out.println("Sum:" + sum); average = (float) sum / n; System.out.println("Average:" + average); } } ``` ## Multi-Dimensional Arrays In such case, data is stored in row and column based index (also known as matrix form). **Syntax to Declare Multidimensional Array in Java:** `dataType[][] arr;` OR `dataType arr[][];` **Example to instantiate Multidimensional Array in Java:** `int[][] ar = new int[3][4];` //3 row and 4 column Here, we have created a multidimensional array named ar. It is a 2-dimensional array, that can hold a maximum of 12 elements, | Column | Column | Column | Column | | :------ | :------ | :------ | :------ | | 1 | 2 | 3 | 4 | | **Row 1** | a[0][0] | a[0][1] | a[0][2] | a[0][3] | | **Row 2** | a[1][0] | a[1][1] | a[1][2] | a[1][3] | | **Row 3** | a[2][0] | a[2][1] | a[2][2] | a[2][3] | **Example:** ```java public class multiDimensional { public static void main(String args[]) { // declaring and initializing 2D array int ar[][] = {{2, 7, 9, 5}, {3, 6, 1, 8}, {7, 4, 2, 3}}; // printing 2D array for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { System.out.print(ar[i][j] + " "); } System.out.println(); } } } ``` **Output** 2 7 9 5 3 6 1 8 7 4 2 3 #### Q. Write a Java program to enter two 3x3 matrices and calculate the sum of given matrices. **Solution:** ```java import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner ed = new Scanner(System.in); int row, col, i, j; System.out.print("Enter number of rows: "); row = ed.nextInt(); System.out.print("Enter number of column:"); col = ed.nextInt(); int[][] a = new int[row][col]; int[][] b = new int[row][col]; int[][] sum = new int[row][col]; System.out.println("Enter first matrix:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { a[i][j] = ed.nextInt(); } } System.out.println("Enter Second matrix: "); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { b[i][j] = ed.nextInt(); } } for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { sum[i][j] = b[i][j] + a[i][j]; } } System.out.println("Sum of two matrices:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { System.out.print(sum[i][j] + " "); } System.out.print("\n"); } } } ``` **Output** Enter number of rows:3 Enter number of column:3 Enter first matrix: 1 6 2 3 7 1 2 3 5 Enter Second matrix: 2 7 1 3 9 5 4 2 8 Sum of two matrices: 3 13 3 6 16 6 6 5 13 ## For Each Loop In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop. **Advantages:** * It makes the code more readable. * It eliminates the possibility of programming errors. **Disadvantages:** * It cannot traverse the elements in reverse order. * We do not have the option to skip any element because it does not work on an index basis. **Syntax** ```java for (data_type variableName: array | collection) { // code block to be executed } ``` For each iteration, the for-each loop takes each element of the collection and stores it in a loop variable. Thus, it executes the code written in the body of the loop for each element of the array or collection. **Example** ```java class Main { public static void main(String[] args) { // create an array int[] numbers = {3, 9, 5, -5}; // for each loop for (int number : numbers) { System.out.println(number); } } } ``` **Output** 3 9 5 -5 Here, the for-each loop traverses over each element of the array numbers one by one until the end. ## Class and Object #### Class A class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind. It is a template or blueprint from which objects are created. To define a class in java we use a keyword class. The general form to define a direct new class is as follows: `<Access><Modifier> class <className> {` //field, constructor, and method declarations `}` The general form to define a new class by extending the class and implementing the interfaces is as follows: `<Access> <Modifier> class <className> extends <superClass> implements <YourInterface> {` //field, constructor, and method declarations `}` **Example** ```java public class Person { //state or field or variable String name = "Jayanta"; int age = 20; //creating the methods of the class void study() { } //methodBody void play() { } //methodBody public static void main(String args[]) { System.out.println("Name of the person: " + name); System.out.println("Age of the person: " + age); } } ``` #### Object An object is an instance of a class. To create an object of a class, first, we need to declare it and then instantiate it with the help of a "new" keyword. **Syntax of creating an object of a class:** ClassName objectName = new ClassName(); **Example:** Person object1 = new Person(); #### Accessing the members of a Java Class: We can access the data members of a class using the object of the class. We just write the name of the object which is followed by a dot operator then we write the name of the data member (either variables or methods) which we want to access. **Syntax:** objectName.variableName; //accessing the variables objectName.MethodName(); //accessing the methods **Example:** object1.age; //accessing the variables object1.play(); //accessing the methods #### Q. Write a Java program to create Rectangle class with data member length and breadth. Include methods getData() and displayArea() in the class. Finally create an object of Rectangle class and display its area. **Solution: ```java import java.util.Scanner; class Rectangle { int l, b; void getData() { Scanner in = new Scanner(System.in); System.out.print("Enter length: "); l = in.nextInt(); System.out.print("Enter breadth : "); b = in.nextInt(); } void displayArea() { int a; a = l * b; System.out.println("Area = " + a); } public static void main(String[] args) { Rectangle obj = new Rectangle(); obj.getData(); obj.displayArea(); } } ``` **Output** Enter length : 5 Enter breadth : 3 Area = 15 ## Constructors A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. At the time of calling constructor, memory for the object is allocated in the memory. Constructor has the same name as its class and is syntactically similar to a method. However, constructors have no return type. All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used. **Types of Constructor:** #### No-Argument Constructors The no-argument constructor of Java does not accept any parameters instead, using these constructors the instance variables of a method will be initialized with fixed values for all objects. **Example:** ```java class Rectangle { double length; double breadth; Rectangle() //No-arg constructor { length = 15.5; breadth = 10.67; } double calculateArea(){ return length*breadth; } } ``` #### Parameterized Constructors A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructor with parameters). **Example:** ```java class Rectangle { double length; double breadth; // Parameterized constructor Rectangle(double l, double b) { length = 1; breadth = b; } double calculateArea(){ return length*breadth; } } ``` ```java class Rectangle_Main { public static void main(String[] args) { double area; Rectangle myrec = new Rectangle(); area = myrec.calculateArea(); System.out.println("The area of the Rectangle: "+area); } } ``` ```java class Rectangle_Main { public static void main(String[] args) { double area; Rectangle myrec = new Rectangle(41,56); area = myrec.calculateArea(); System.out.println("The area of the Rectangle: "+area); } } ``` ## Method Overloading If a class has multiple methods having the same name but different in parameters (different number of parameters, different types of parameters, or both), it is known as Method Overloading. When a method is invoked, Java matches up the method name first and then the number and type of parameters to decide which one of the definition is execute. **Example** ```java public class Sum { // Overloaded the method sum(). This sum takes two int parameters as input public int sum(int a, int b) { return (a + b); } // Overloaded the method sum(). This sum takes three int parameters as input public int sum(int a, int b, int c) { return (a + b + c); } // Overloaded the method sum(). This sum takes two double parameters as input public double sum(double a, double b) { return (a + b); } // Main code public static void main(String args[]) { Sum s = new Sum(); System.out.println(s.sum(3, 2)); System.out.println(s.sum(2, 2, 4)); System.out.println(s.sum(10.5, 20.5)); } } ``` **Output** 5 8 31.0 In this example, the number of parameters as well as its data type is changed to overload the method. If the parameters provided are both int then the first sum method is executed. If there are three parameters, all int then the second method is invoked. In case two double data type parameters are given then the third method is invoked. ## Static Modifier The static keyword is a non-access modifier used for methods and variables. Static methods/variables can be accessed without creating an object of a class. The main purpose of using the static keyword in Java is to save memory. When we create a variable in a class that will be accessed by other classes, we must first create an instance of the class and then assign a new value to each variable instance - even if the value of the new variables are supposed to be the same across all new classes/objects. But when we create a static variables, its value remains constant across all other classes, and we do not have to create an instance to use the variable. This way, we are creating the variable once, so memory is only allocated once. #### Static Methods: Static methods are also called class methods. It is because a static method belongs to the class rather than the object of a class. And we can invoke static methods directly using the class name. For example, ```java class StaticTest { // non-static method int multiply (int a, int b) { return a * b; } // static method static int add (int a, int b) { return a + b; } } public class StaticMethodDemo { public static void main(String[] args) { // create an instance of the StaticTest class StaticTest st = new StaticTest (); // call the nonstatic method System.out.println (" 5 * 5 = " + st.multiply (5,5)); // call the static method System.out.println (" 5 + 3 " + StaticTest.add (5, 3)); } } ``` There are two main restrictions for the static method. They are: 1. The static method cannot use non-static data members or call the non-static method directly. 2. this and super cannot be used in a static context. #### Static Variables: If we declare a variable static, all objects of the class share the same static variable. It is because like static methods, static variables are also associated with the class. And, we don't need to create objects of the class to access the static variables. For example, ```java class Test { // static variable static int max = 10; // non-static variable int min = 5; } public class Main { public static void main(String[] args) { Test obj = new Test(); // access the non-static variable System.out.println("min + 1 = " + (obj.min + 1)); // access the static variable System.out.println("max + 1 = " + (Test.max + 1)); } } ``` #### Access static Variables and Methods within the Class We are accessing the static variable from another class. Hence, we have used the class name to access it. However, if we want to access the static member from inside the class, it can be accessed directly. For example, ```java public class Main { // static variable static int age; // static method static void display() { System.out.println("Static Method"); } public static void main(String[] args) { // access the static variable age = 30; System.out.println("Age is " + age); // access the static method display(); } } ``` ## Inheritance Inheritance is the mechanism of deriving a new class from an existing class. The existing class is known as the superclass or base class or parent class and the new class is called subclass or derived class or child class or extended class. The subclass inherits some of the properties from the superclass and can add its own properties as well. extends is the keyword used to inherit the properties of a class. **Syntax:** ```java class BaseClass { //methods and fields } class DerivedClass extends BaseClass { //methods and fields } ``` #### Types of Inheritance 1. **Single Inheritance**: In single inheritance, a class is derived from only one existing class. ```java class A { //methods and fields } class B extends A { //methods and fields } ``` **Example:** ```java class A { void func1() { System.out.println("Method funcl belongs to parent class A"); } } class B extends A { void func2() { System.out.println("Method func2 belongs to child class B"); } } class Single { public static void main(String[] args) { B obj = new B(); obj.func2(); obj.funcl(); // Note that object of class B is used to invoke funcl() } } ``` **Output:** Method funcź belongs to child class B Method funci belongs to parent class A 1. **Multilevel Inheritance:** The mechanism of deriving a class from another subclass is known as multilevel inheritance. ```java class A { //methods and fields } class B extends A { //methods and fields } class C extends B{ //methods and fields } ``` **Example:** ```java class A{ void func1() { System.out.println("Method funcl belongs to parent class A"); } } class B extends A{ // Notice the extends keyword ( inheriting B from A) void func2() { System.out.println("Method func2 belongs to intermediate class B"); } } class C extends B{ void func3 () { System.out.println("Method func3 belongs to child class C"); } class Multilevel{ public static void main(String[] args) { C obj = new C(); obj.func3(); obj.func2(); obj.funcl(); } } ``` **Output:** Method func3 belongs to child class C Method func2 belongs to intermediate class B Method funci belongs to parent class A 1. **Hierarchical Inheritance:** In this type, two or more classes inherit the properties of one existing class ```java class A { //methods and fields } class B extends A { //methods and fields } class C extends A{ //methods and fields } ``` **Example:** ```java class Values { int len, bre; void getValue(int l, int b) { len = l; bre = b; } } class Rect extends Values { void recArea() { System.out.println("Area of rectangle = " + (len * bre)); } } class Square extends Values { void sqArea() { System.out.println("Area of Square " + (len * len)); } } class Heirarchical { public static void main(String[] args) { Rect r = new Rect(); Square sq = new Square(); r.getValue(10, 20); r.recArea(); sq.getValue(10, 10); sq.sqArea(); } } ``` **Output:** Area of rectangle = 200 Area of Square = 100 1. **Multiple Inheritance:** When one class inherits multiple classes, it is known as multiple inheritance. ```java ClassA ClassB ClassC ``` Java doesn't support multiple inheritance. We can achieve multiple inheritances only with the help of Interfaces. #### Q. Why multiple inheritance is not supported in Java? **Solution:** In Java multiple inheritance is not supported because it may become ambiguous in case if more than one parent class have same method. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and we call it from child class object, there will be ambiguity to call method of A or B class. To prevent such situation, multiple inheritances is not allowed in java. ## Access Modifiers The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. There are four types of Java access modifiers: 1. **Private**: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. E.g. ```java class A { private int data = 40; private void msg() { System.out.println("Hello"); } } public class B { public static void main(String args[]) { A obj = new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } ``` 2. **Default**: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If we do not specify any access level, it will be the default. E.g. ```java //save by A.java package pack; class A { void msg() { System.out.println("Hello"); } } //save by B.java package mypack; import pack.*; public static void main(String args[]) { A obj = new A(); //Compile Time Error obj.msg(); //Compile Time Error } ``` 3. **Protected**: The access level of a protected modifier is within the package and outside the package through child class. If we do not make the child class, it cannot be accessed from outside the package. E.g. ```java

Use Quizgecko on...
Browser
Browser