Docsity

Basic concepts of Java and some problem, Transcriptions of Computer science

Toggle sidebar
bg1
Introduction To Java
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems in 1991. Language was initially called “Oak” but
was renamed “Java” in 1995. They wanted it primarily to control microprocessors
embedded in consumer items such as cable set-top boxes, VCR's, toasters, and also for
personal data assistants (PDA). Java is an object-oriented, class-based, concurrent,
secured and general-purpose computer-programming language. To serve these goals,
Java needed to be:
Simple : Java has a concise, cohesive set of features that makes it easy to learn
and use.
Secure : Java provides a secure means of creating Internet applications.
Portable : Java programs can execute in any environment for which there is a
Java run-time system.
Object-oriented: Java embodies the modern, object-oriented programming
philosophy.
Robust : Java encourages error-free programming by being strictly typed and
performing run-time checks.
Multithreaded : Java provides integrated support for multithreaded
programming.
Architecture-neutral : Java is not tied to a specific machine or operating system
architecture.
Interpreted : Java supports cross-platform code through the use of Java
bytecode.
High performance : The Java bytecode is highly optimized for speed of
execution.
Distributed : Java was designed with the distributed environment of the Internet
in mind.
Dynamic : Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time
Types of Java Applications
There are mainly 4 types of applications that can be created using Java programming:
Standalone Application
Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b

Partial preview of the text

Download Basic concepts of Java and some problem and more Transcriptions Computer science in PDF only on Docsity!

Introduction To Java

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems in 1991. Language was initially called “Oak” but was renamed “Java” in 1995. They wanted it primarily to control microprocessors embedded in consumer items such as cable set-top boxes, VCR's, toasters, and also for personal data assistants (PDA). Java is an object-oriented, class-based, concurrent, secured and general-purpose computer-programming language. To serve these goals, Java needed to be:  Simple : Java has a concise, cohesive set of features that makes it easy to learn and use.  Secure : Java provides a secure means of creating Internet applications.  Portable : Java programs can execute in any environment for which there is a Java run-time system.  Object-oriented: Java embodies the modern, object-oriented programming philosophy.  Robust : Java encourages error-free programming by being strictly typed and performing run-time checks.  Multithreaded : Java provides integrated support for multithreaded programming.  Architecture-neutral : Java is not tied to a specific machine or operating system architecture.  Interpreted : Java supports cross-platform code through the use of Java bytecode.  High performance : The Java bytecode is highly optimized for speed of execution.  Distributed : Java was designed with the distributed environment of the Internet in mind.  Dynamic : Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

 Standalone Application

Standalone applications are also known as desktop applications or window-based applications. These are traditional software that we need to install on every machine. Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

 Web Application

An application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java.

 Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an enterprise application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for creating enterprise applications.

 Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications.

Java Virtual Machine

The key that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, the Java Virtual Machine is an interpreter for bytecode. JVM is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. . Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments. The reason is straightforward: only the Java Virtual Machine needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember that although the details of the JVM will differ from platform to platform, all understand the same Java bytecode. When a program is interpreted, it generally runs substantially slower than the same program would run if compiled to executable code. However, with Java, the differential between the two is not so great. The use of bytecode makes it possible for the Java run-time system to execute programs much faster than one might expect. The JVM performs the following main tasks:  Loads code  Verifies code  Executes code  Provides runtime environment

  1. Runtime Environment
  2. API(Application Programming Interface) Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA). 4. Secured Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:  No explicit pointer  Java Programs run inside a virtual machine sandbox  Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources.  Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.  Security Manager: It determines what resources a class can access such as reading and writing to the local disk. 5. Robust The English meaning of Robust is strong. Java is robust because:  It uses strong memory management.  There is a lack of pointers that avoids security problems.  Java provides 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. 6. 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.

7. Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. 8. High-performance Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc. 9. 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. 10. Multi-threaded A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc. 11. Dynamic Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  1. Bootstrap ClassLoader : This is the first classloader which is the super class of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.

C:\ cd JavaProg

  1. To compile this program write this command C:\ JavaProg> javac hello.java After successful compilation javac will create a class file named hello.class in JavaProg Folder. It contains the bytecode version of the program. To see it type ‘dir’ command
  2. On successful compilation run the programme by typing C:\ JavaProg> java hello Notes :  When Java source code is compiled, each individual class is put into its own output file named after the class and using the .class extension. This is why it is a good idea to give Java source files the same name as the class they contain—the name of the source file will match the name of the .class file. When we execute the Java interpreter as just shown, we are actually specifying the name of the class that we want the interpreter to execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it will execute the code contained in the specified class.  public static void main (String args[]) All Java applications begin execution by calling main( ). The public keyword is an access specifier. An access specifier determines how other parts of the program can access the members of the class. main( ) must be declared as public , since it must be called by code outside of its class when the program is started.  static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory.  The keyword void simply tells the compiler that main( ) does not return a value.  System.out.println("Welcome to the World of Java"); This line outputs the string "Java drives the Web." followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the string which is passed to it. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. Thus, System.out is an object that encapsulates console output.

Program 2: Variables and Constants // Area of circle by declaring 2 variables named radius and area public class Circle { public static void main(String[] args) { double radius,area; radius=3.0; area= 3.14159* radius*radius; System.out.println("For radius "+ radius); System.out.println("The area is “+area); } }

Output:

For radius 3.

The area is 28.

Program 3 : Use of a constant public class circle { public static void main(String[] args) { double radius,area; final double PI = 3.14159; radius=3.0; area= PIradiusradius; System.out.println("For radius "+ radius); System.out.println("The area is “+area); } }

Output:

For radius 3.

The area is 28.

OUTPUT:

Before the call, variable time is 3 Inside the method n= After the call,variable times is 3

Object Oriented Programming Concepts

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object- Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation Apart from these concepts, there are some other terms which are used in Object-Oriented design:  Coupling  Cohesion  Association  Aggregation  Composition Object Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system. An object has three characteristics:  State: represents the data (value) of an object.

Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.  Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely. For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior. Class Collection of objects is called class. It is a logical entity. A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space. A class in Java can contain:  Fields  Methods  Constructors  Blocks  Nested class and interface An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class. A variable(Field) which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable. Accessing an instance variable from outside the object requires a reference object. A variable (Field) which is created inside the class as static but outside the method is known as an class variable. This is shared by all objects. It does not requires an object reference to access instead class name is used as reference to access the class variables. Inheritance When one object acquires all the properties and behaviors of a parent object , it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

public static void main (String[] args) { circle mycircle = new circle(); System.out.println("For the radius" + mycircle.radius ); System.out.println("The area of the circle is " + mycircle.findarea()); } } class circle { double radius = 1.0; double findarea() { return radiusradius3.14159; } } OUTPUT For the radius 1. The area of the circle is 3. Note : Reference Variable: Example circle c1 = new circle(); // create the object c circle c2 = c1; // create a reference object c Here c2 is being assigned a reference to a copy of the object referred to by c1. That is c and c2 refer to the same object. Example 7: Create a class POINT which defines two dimensional point. import java.util.*; class mymain { public static void main (String[] args) { point p1 = new point(); point p2 = new point(); p1.input(); p2.input(); p1.output(); p2.output(); float d=p1.distance(p2); System.out.println("Distance between two points is “+d);

class point { int x, y; void input() { Scanner sc = new Scanner(System.in); System.out.println(“Enter x “); x=sc.nextInt(); System.out.println(“Enter y “); y=sc.nextInt(); } void output() { System.out.println(“(“+x+”,”+y+”)”); } float distance(point p) { float d; d=Math.sqrt((p.x-x)(p.x-x)+(p.y-y)(p.y-y)); return(d); } }

Constructor

It is a special method which automatically called when an object is created. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by JVM. It has the following characteristic:  Constructor do not have return type (not even void)  They have same name as class name.  Constructor cannot be inherited though derive class can call the base class constructor.  Java automatically call the constructor when the object is created.  A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

Constructor Overloading in Java In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. Example class Student { int id; String name; int age; Student(int i,String n) { id = i; name = n; } Student(int i,String n,int a) { id = i; name = n; age=a; } void display() { System.out.println(id+" "+name+" "+age); } public static void main(String args[]) { Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan",25); s1.display(); s2.display(); } }

Difference between constructor and method in Java There are many differences between constructors and methods. They are given below. Java Constructor Java Method A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object. A constructor must not have a return type. A method must have a return type. The constructor is invoked implicitly. The method is invoked explicitly. The Java compiler provides a default constructor if you don't have any constructor in a class. The method is not provided by the compiler in any case. The constructor name must be same as the class name. The method name may or may not be same as the class name.

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in Java. They are:  By constructor  By assigning the values of one object into another  By clone() method of Object class In this example, we are going to copy the values of one object into another using Java constructor. Example class Student { int id; String name; Student6(int i,String n) { id = i; name = n; } Student6(Student6 s) { id = s.id;

return( 3.14rr); } float area( float l, float b) { return( lb); } int area(int a) { return(aa); } } Class overloaddemo { Public static void main(String a[]) { Shape A = new Shape(); float circle = A.area(7.2); System.out.println(“Area of circle is “+ circle); float rect = A.area(2.0 , 8.4); System.out.println(“Area of rectangle is “+ rect); float square = A.area(2 , 8); System.out.println(“Area of square is “+ square); } } OUTPUT Area of circle is 162. Area of rectangle is 16. Area of square is 16

Array

Declaration : int[] arrname; Creation : arrname = new int[10]; Create & initialize : int[] arrname = { 12, 34 , 78, 90, 34, 50} arrname.length  length of the array.

Access Control

Java’s access specifiers are public, private, protected. It also defines a default access level. When a member is defined as public then that member can be accessed by any other code. When a member is defined as private then that member can be accessed by other member of its class. When no access specifier is used then by default the member of a class is public within its own package, but can not be accessed outside its package.

Program 9 : Demonstration of Access Control Class Test { int a ; // Default member public int b; // Public member private int c; // private member void setc(int x) { c=x; } int getc() { return(c); } } class accessdemo { public static void main( String a[]) { Test ob = new Test(); ob.a=10; // OK because ‘a’ is default; ob.b=20; // OK because ‘b’ is public // ob.c=30 ; // Error because ‘c’ is private ob.setc(30); // OK because setc is deault System.out.println(“a b and c : “ + ob.a+” “ +ob.c+” “ + ob.getc()); } } Program 10 : Imeplementation of Stack class stack { private int stck[]; private int top; stack(int size) // Constructor { stck = new int[size]; top = - 1; } void push(int item) { if (top==stck.length-1) System.out.println(“Stack is full “); else stck[++top]=item; }