• No results found

CoreJava iNetSolv

N/A
N/A
Protected

Academic year: 2021

Share "CoreJava iNetSolv"

Copied!
191
0
0

Loading.... (view fulltext now)

Full text

(1)

JAVA

Object Oriented Program is a programming approach in which a problem domain is characterized as a set of objects that have a specific attributes and behavior. The objects are manipulated with a collection of functions called methods or services. The objects are classified into classes and subclasses. (or)

An Object Oriented Programming organizes a program around its data, i.e., objects and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

Java is an Object Oriented Programming (OOP) language used to design an application, which will run securely over the network1 and work on wide range of platforms.

J2SE: - J2SE stands for Java 2 Standard Edition, it is a specification used to develop fundamental java application they may be standard or network.

J2SE = Core Java + Advanced Java J2SE: - Java 2 Standard Edition J2EE: - Java 2 Enterprise Edition

J2EE: - J2EE stands for Java 2 Enterprise Edition, it is a specification used to develop business solutions for network (or) J2EE is a specification that provides an environment to run the web components and the enterprise components.

J2ME: - Java 2 Micro Edition

J2ME: - J2ME stands for Java 2 Micro Edition, it is a specification used for developing wireless and Embedded System. Embedded System is software, which directly installed into hardware.

Difference between Java 1.4.1. and Java 1.5

[www.sunjava.com, www.javasoft.com] Core Java – Desktop Java

NIC – Network Interface Card

Novel Network: - Net based softwaress Ex: - Windows NT, UNIX.

Protocol: - This is also a program; it is a specification of set of rules to be followed by a computer in network.

When to send/receive data How to send/receive data

Hand Shaking: - This means two Computers establishing a connection communicating with each other and finally disconnecting is called Hand shaking.

A Packet represents a group of bytes. IP means Internet Protocol address this is unique address this is given to Computers.

TCP/IP: - Transmission Control Protocol/Internet Protocol.

Client: - A Client is a machine that sends a request for some services to other Computer.

Server: - Server is a machine that receives requests from the Clients and provides services to the Client requests.

The main advantage of a network is resources sharing.

Web application: - A web application is a collection of Servlets, HTML pages, Classes and other resources that can bundle and run on the multiple Containers from multiple Vendors.

Resources Sharing:

- Sharing memory

11 Network: - Complete network is interconnection & Autonomous systems that are used for communication or exchange of information between the two systems in the network, the systems, which are connected in the network, are called as hosts.

Frame

Packet

(2)

 Sharing data

 Sharing software

 Sharing hardware

 Sharing Processor

1969 Department of Defence (DOD), USA, Ken Thompson is introduced network. This network is called ARPANET.

AT&T – Advanced Telephone Communication & Technology USA based Telephone Company.

Hyundai, British Telecom are also Telephone companies, these three companies are giant of the Telephone.

ISP: - It stands for Internet Service Provider. ISP is a person or an organization, who provides connection into internet. ISP should take direct connection to internet. (www.internic.com).

Bandwidth is a group of frequency.

 American Congress Library is a biggest Library in the World; the second biggest Library is Lenin Glad Library in Masco, (Russia).

Q) What is an Interface? *****

Ans: - An Interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but doesn’t implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior.

An interface is a named collection of method definitions (without implementations). An interface can also declare constants.

Internet: - Internet is a network of Computers existing on the earth. Internet is a global network of all networks existing on the earth.

Connecting Internet types: - Dialup Connection: -

 Dialup connection main advantage is affordable to any one.

 Disadvantage of Dialup connection is slow.

 There is no security for data.

2. Leased line Connection: - It is a direct connection to internet.

Server

Another Computer

AT & T

British Telecom

Hyundai

ISP

50GBPS

Satellite

(3)

Advantages: -

 High Security for data

 Lightening Speed (i.e. high speed) Disadvantages: -

Highly expensive.

The web browser2 software is installed on Internet Client.

Ex: - Internet Explorer, Mozilla, Fire fox, Netscape Navigator etc…

The software that should be installed on Internet Server is Web Server.

Web Server: - A web server is a server that provides the implementation of HTTP protocol. Ex: - Internet information Server (IIS), Apache Web Server, etc…

Application Server: - An Application Server is a product that provides the facilities like taking care of transactions, taking care of security and simplifies the development of business logic (or) Application servers provides you with common middleware services, such as resource pooling, networking and more. Application server allows you to focus on your application and not worry about the middleware you need for a robust server side deployment.

Ex: - Microsoft Transactions Server (MT Server) from Microsoft, EJB containers like WebLogic, WebSphere, JBoss etc…

Hypertext Transfer Protocol (HTTP) is widely used protocol on internet.

File Transfer Protocol (FTP), when we download a file from Internet.

Simple Mail Transfer Protocol (SMTP) is used to send mails on the internet.

Post Office Protocol (POP) is used to receive mails. Programmer has:

-1. To develop a web browser

2. To increase the capabilities of web browser 3. To develop a web server

4. To increase the capabilities of the web server 5. To develop protocol

Translator is a program that converts a computer program into machine language (Electric Pulses). There are 3 types of translators

-1. Interpreter Interpreter translates line by line of computer program 2. Compiler Compiler translates all lines of program at a single time

3. Assembler Assembler translates assembly language into machine language

C, C++, are not portable3 programs, they are system dependent because they can be executed

only on that system where they are developed. The first microprocessor is - 4 0 0 4

The next microprocessors are follows as below 8 0 0 8 8 0 8 5 8 0 8 6 8 0 2 8 6

2 Web browser: - The web browser is a GUI based software is installed on Internet Client that allows the user to

navigate www and web pages on Computer screen. 3 Portability: - Yielding on any Computer

x.c

x.obj

x.exe

Machine code Convert the Header file Full pledged machine code language instructions

(4)

8 0 3 8 6 8 0 4 8 6

8 0 5 8 6x, PI, PII, Celeron, PIII, AMD, PIV, PIV Pro

Why Java is suitable for Internet

The size of each instruction is 1 byte or 8 bits.

There are around 210 byte code instructions are available

Byte code instruction is understand by JVM4 (Java Virtual Machine). Components of JVM

JVM

 Sun Microsystems is developed the JVM program.

JVM convert byte code instruction into machine code.

 JVM understand every byte code instructions. 4 JVM: - Java Virtual Machine is a program. It is not a machine.

x.java

x.class

JVM

It consists

byte code

format

JVM

JVM

P

IV

Celeron

Cyrix

Execution Engine Security Manager Garbage Collector Byte code verifier Class

(5)

 JVM will understand the byte code instruction & it will convert the byte code instructions into PIV processor understandable machine language instructions.

JVM will convert the byte code instructions into any type of processor understandable machine language instructions.

Java programs system independent.

JVM is system dependent.

 Depending on operating system we have to download the operating system related JVM program.

.class file is system independent.

 JVM is making as Java system independent.

 Portability means giving same results on any type of system or machine. Security Problems on Internet: -

1. Eves dropping: - Reading others data illegally on Internet, is called Eves dropping.

2. Tampering: - Not only reading others data but also modifying it on Internet, is called Tampering. 3. Impersonation: - A person acting as another person on Internet is called impersonation.

4. Virus: - Virus is a harmful program that can damage data, software & hardware of a system.

Virus was first developed by Pakistani’s. Virus will spread to *.exe, *.sys, *.doc. but *.txt files cannot carry virus.

 Solution for eves dropping & tampering encryption/decryption. Encryption means converting data into understandable data. Decryption means converting data back to readable form.

 For impersonation, solution is digital signature file, containing personal information for identify the person in encrypted form. Digital signatures are developed in java.

Solution for virus is .class file. Security manager is program that identifies illegal code and information security polices. A .class is a text file virus can’t be affected.

Why Java is suitable for Internet:

- Security problems on Internet are eliminated through java.

 Java is a system independent; Java is executable on any platform.

In 1990, Sun Microsystems inc., USA is developed software for remotes. (James Gosling). In 1993, Oak language is developed, by that time some company is registered Oak name, for this reason they named as “Java”.

In 1995, Sun world conference has given entire details of Java. Features of Java:

-1. Simple: - Java is a simple programming language, learning and practicing java is easy because of its resemblance (Similarity) with C, C++.

2. Object Oriented: - Unlike C++, Java is a purely object oriented programming language. Java = C++ - Complexity

“An object is existing of everything in the world is an Object”. An object has properties & performs actions.

Object initialization process:

Default values → initialization expressions → initialization blocks → constructors Default values:

-float, double - 0.0F,0.0 boolean - false

Reference variable - null (not referring any object)

Char - ‘\u000’ (or) a space

String - Null

My class - Null

3. Distributed: - Java is designed for use on networks. It has extensive libraries, which work in agreement with TCP/IP5. Java uses protocols like HTTP6 & FTP.

5 TCP/IP: - Transmission Control Protocol/Internet Protocol. 6 HTTP: - Hypertext transfer Protocol.

(6)

4. Robust: - Java programs will not crash because of its exception handling and its memory management feature.

Pointers are eliminated from Java due to: - 1. These are lead to complex programs 2. Using pointers harmful programs are written. 3. Pointers may crash a program.

 Method is a function; Function represents set of instructions to perform the results. A method must be starts with lowercase. A method will returns a void or any valid return type. A method can be inherited and it can be overloaded or overridden. A method has called explicitly.

Function can be written inside & outside of the class, but a method is a function, it is written only inside of a class. A function can be called & executed itself.

Q) What is the difference between method and function? *****

Ans: - A method is a function written only inside of a class but functions can be written any where in class i.e. inside or outside of the class. In java we will write only methods. Writing a function outside the class is not possible in java.

Methods or functions can store only some temporary variables or local variables, but not permanent variables.

A class is a model or idea or plan to create objects or Class is a group of objects. Class doesn’t exist really because it is only an idea but objects exist really.

 A class will also contain variables & methods.

 An object will also contain variables & methods.

 In every java program we must create a single class.

 C++ is not purely Object oriented programming

 Internet is a distributed technology.

 Java is suitable for distributed technology.

 Robust means strong, in java we can write strong programs.

 Exception means runtime error

 JVM will allot memory to what ever we required memory.

 Unused memory released or free it by JVM

 Garbage Collector will delocate or removes memory for unreferenced or unused objects and variables.

 Garbage Collector can be called explicitly but there no gurantee that the garbage collector executes or not at that point.

Q) What algorithm is used by garbage collector to remove variables or objects from memory? ***** Ans: - Mark & Sweep algorithm.

Q) What is the difference between .exe and .class file? *****

Ans: - .exe file contains machine language instructions for the microprocessor. It is system dependent. .class file contains byte instructions for JVM. It is system independent.

 In JVM class loader sub system will allot the memory required for program.

 Garbage memory delocates the memory.

5. Secure: - Java is designed for use on internet. Java enables the construction of virus-free, tamper free systems.

6. Architecture Neutral: - Java’s byte code is not machine dependent. It can be run any machine with any processor and any operating system.

7. Portable: - Java does not have implement-dependent aspects. So the results will be same on all machines. Portable means yielding same results on different machines.

8. Interpreted: - Java programs are compiled to generate bye code. This byte code can be downloaded and interpreted by the interpreter. JVM contain interpreter.

(7)

9. High performance: - Along with interpreter there will JIT (Just in time compiler), which enhances the speed of execution.

Variable: - An item of data named by identifier. Each variable has a type, such as int or object and a scope.

Reference Variable: - A data element whose value is in an address.

Local Variable: - A data item known within a block, but inaccessible to the code outside the block.

For example, any variable defined within a method is a local variable and can’t be used outside the method.

A local variable life cycle ends when the execution of method completed. A local variable should declared within a method body and it must be initialized when we are declaring in a method, because it doesn’t takes default values.

Path Variable: - It is exterenal command file. A path variable is used to specify where the executable files are. Ex: - javac.exe, java.exe, javap.exe etc.

Argument: - A data item specified in a method called an argument. An argument can be a literal value, a variable or an expression (or) an argument is a value that is passed to the method when it is invoked. Parameter: - While defining a method, variables passed in the method called as parameter (or) Parameters are variables defined by method that receives values when a method is called.

 Parameters are useful to pass the variables from objects to the constructor.

 Method parameters are local variables to receive the data from out side for method.

Parameters are useful to receive the values from outside to main method.

What is the difference between parameter and argument? *****

Ans: - While defining method, variables passed in the method called as parameter. While using those methods, values passed to those variables called arguments.

Process: A virtual address space containing one or more threads (or) a program under execution is also called as process.

Peer: - In networking, any functional unit in the same layer as another entity.

Expression: - An expression is a series of variables, operators, and methods calls, (constructed according to the syntax of the language) that evaluates to single value.

How would you detect and minimise memory leaks in Java:

-In Java memory leaks are caused by poor program design where object references are long lived and the garbage collector is unable to reclaim those objects.

Detecting memory leaks:

Use tools like JProbe, OptimizeIt etc to detect memory leaks.

Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on UNIX systems.

Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime class. Place these calls in your code strategically for pre and post memory recording where you suspect to be causing memory leaks. An even better approach than a utility class is using dynamic proxies or Aspect Oriented Programming (AOP) for pre and post memory recording where you have the control of activating memory measurement only when needed.

Minimising memory leaks:

In Java, typically memory leak occurs when an object of a longer lifecycle has a reference to objects of a short life cycle. This prevents the objects with short life cycle being garbage collected. The developer must remember to remove the references to the short-lived objects from the long-lived objects. Objects with the same life cycle do not cause any issues because the garbage collector is smart enough to deal with the circular references.

(8)

Class loader subsystem does the following things: -1. It will load .class file into memory (RAM) 2. It will verify byte code of that .class file.

3. It will allot the required memory for the program.

This memory is divided into five parts; they are called runtime data areas. 1. Method area: - It stores class code, static variables, static blocks and method code. 2. Heap area: - Objects are created on Heap. JVM creates objects on Heap.

3. Java Stacks: - Java stacks are used to execute the java methods. Java stacks will have frames. On each frame a separate method is executed.

4. PC Registers: - These registers contain the address of that instruction to be executed by the processor. 5. Native method stacks: - It is a method written in a language other than java. Native method stacks places when native methods are executed.

Note: - Native method interface links header files to a native method while it is being executing.

Execution engine contains interpreter & JIT compiler, which translates byte code into machine language.

How JIT compiles converts byte codes. Ex: - print a; 2sec

print b; 2sec

Repeat the loop 10times; print a; 2 + 2

 Hotspot is the block code of given to JIT compiler for execution.

10. Multithread: - Thread means an execution or processing group of statements. Executing different parts of a program simultaneously at a time by using more than one thread is called Multithreading. This is an essential feature of to design server side programs.

11. Dynamic: - It means at runtime, we can develop programs in java, which dynamically change on Internet. (Ex: Applets).

 In java entire memory will be dynamic memory. Java Programming: -

• Comments represent description of the features of a program.

The main advantages of comments are readability7 of the program is increased.

There are 3 types of comments in Java. They are 7 Readability = Understandability. Method area Heap Java Stacks PC registers Native method stacks Class files

runtime data areas Class Loader Subsystem Execution Engine Native method interface Native method libraries For Interpreter

(9)

1. Single line comments: - It represents only one line as comment. Single line comments start with //. Ex: - //Welcome INet Solv

//welcome to Java

2. Multi line Comments: - They represents a group of lines as comment. They starts with /* and end with */ Ex: - /*Welcome to India*/

3. Java documentation Comments: - They starts with /** and end with */. Ex: - /**Welcome to BTCE*/

 These comments are useful to create .html documents from .java programs.

API Document: - API stands for Application programming Interface. It is a .html document that contains description of all the features of a software or a product or a technology. API document does not contain code. Javadoc complier is used for this.

Comments are non executable statements. These 3 types of comments are not executable by java compiler or JVM compiler.

 In Java we can define/write any number of classes in a single class. Out of n number of classes we are writing in a single class only one can be defined as public class, because the name of the class should be public class.

 If we need all the classes as public we have to decalred/write sepeartely each class as public. Example Program: -

/*This is our first Java program. To display a message Author: INet Solv team Version8: V 1.0

Project: Proxyz 1.11 */

//Starting a program in Java import java.lang.system;

import java.lang.string; or in the place of two steps directly we can write as below import java.lang.*9; class First { main10() { } }

Q) What is the difference between #include and import statements? *****

Ans: - #include makes C/C++ compiler to copy the header file into a C/C++ program. Thus it wastes the memory and processor time.

import will makes the JVM to go to a particular class, it executes the code there and then it comeback to the program and substitute the results in the program.

JRE: - It stands for Java runtime environment.

JRE = JVM + Java library

If java programs have to run we required the JVM and java library. JVM will starts execution of java program from main method only.

8 Version V 1.0: - 1 represents major version and 0 represents minor version. 9 * means all the class/interfaces are java.lang are known available. 10 main() is a called as main method. It is a group of statements.

It is a sub directory & it contains

group of class/interfaces

Java library

It contains group of packages

Packages

Class/Interfaces

Methods

(10)

 String represents group of characters.

 Array represents group of elements. Array denotes with [ ]

 The values passed to the main method are called command line arguments.

 Void means no value (i.e. it returns no value). import java.lang.*; class First { main11() { } }

To call method there are two steps:

-1. To create on object to the class to which method belongs Classname obj = new12 Classname();

Ex: - First f = new First(); (∴f = object) 2. Call the method using object name.methodname

Obj.methodName(); Ex: - f.main();

Objects are created dynamically (runtime) by JVM

Static method: - It is a method that can be called and executed without creating an object.

Public: - It means available outside the object. JVM will not run the public without writing String args[]. JVM could not executes the main method.

For single character in java we have to write in single quotations like as ‘a’ and for integer don’t write in any quotations.

System13.out14: - Out is a variable of a system class. It is a static variable or filed.

 Save the name with in double quotations to avoid the extension of .txt. System.out.println(): -

System: - System is a predefined final class which is defined in java.lang package that provides the access to the system resources like Keyboard, monitor etc… and to get and set the properties associated with java runtime system. All the methods in the System class are static methods.

System Class: - A System class will have static members, they are as follows below

 PrintStream out, err

 InputStream in;

 arrayCopy(Object[ ], st, end, Object[ ], st)

 exit(int)

 loadLibrary(String)

 get/setSecurityManager(SecurityManager)

 String getProperty(String)

 String getProperties(String str) (getProperties() method is usefull to get the JVM name, version, properties of JVM and etc.).

 Properties getProperties() (Property is a class in java.util package and getProperties() method is usefull to set/get the property of a class, etc.).

 gc()

out: - out is a static variable defined in a System class of the type PrintStream class, which provides all of the formatting capabilities we have been using from the system file handler or out is the PrintStream object.

println(): - println() is a built-in overloaded method in the out object or the PrintStream object supports the print() or println() methods for all data types.

We can provide a security for a class as below: public static void main(String args[ ]){ 11 main is a method, that is a group of statements. 12 new is an operator.

13 System is a class. 14 Out is a variable.

(11)

System.setSecurityManager(new SecurityManager()); ---} To Compile: -C:\rnr>javac First.java↵ C:\rnr>java First↵ Welcome to java

 Class, interface contains methods.

Function is written inside & outside of the class, but methods are written only inside of the class.

 Command line arguments are passed some values to the main method.

 Main method does not return any value. Void means no value.

 JVM always starts execution of the statements inside of the main method.

 Public is written to make available main method to the JVM. Ex 2: -

//To find sum of two numbers

import java.lang.*; (∴* is a String class) class Sum

{ (

{ ----This is for starting of class) public static void main(String args[ ]) (

String args[ ] is a parameter)

{

//Variables int a, b;

//Store data into variables a = 10;

b = 15;

//Now find sum int c = a + b; //display the result

System.out.println(“Sum = ”,+c); }

} (∴} ----This is for ending of class) (or)

//To find sum of two numbers import java.lang.*;

class Sum {

public static void main(String args[ ]) {

//Variables int a, b;

//Store data into variables a = 10;

b = 15;

//display the result

System.out.println(“Sum = ” + (a+b)); }

}

Save the above file (with class name compulsory) as “Sum.java”

C:\rnr>javac Sum.java↵ (This is for program compilation) C:\rnr>java Sum.java↵ (This is to run the program)

Note: -

1. print method displays the results and keeps the cursor in the same line. 2. println method displays the results and then throws the cursor to the next line.

S. No. Back slash codes

(12)

1. \n New line 2. \r Enter key 3. \t Horizontal tab 4. \b Backspace key 5. \\ \ 6. \“ “ 7. \‘ ‘

 In java every statement must end with semi colon (;).

 Java is case sensitive programming language. Naming Conventions in Java: -

1. Each word of class names and interface names start with a capital letter. Ex: - String, StringBuffer, DataInputStream, ActionListener etc…

2. Packages names in java are written in all small letters. Ex: - java.awt, java.io, java.swing etc…

3. Method names start with a small letter, then each word start with a capital letter. Ex: - println(), getChars, readLine(); getNumberInstance() etc…

4. Variables names also follow the above rule. Ex: age, empName, employee_Net_Sal etc…

5. Constant variables should be written using all capital letters. Ex: - PI, MAX_VALUE, FONT15.BOLD16

Note: - java.lang is a package that is by default imported into every java program. The other packages must be imported in java program.

Important packages of Java: -

1. java.lang: - This package got primary classes and interfaces essential for java language. It consists of wrapper classes, strings, multithreading etc.

 Wrapper classes are useful to create objects

 String is a class in java

 Multithreading means create several threads (processes executing) at a time.

2. java.util (util = utility): - This package contains useful classes and interfaces like stack, LinkedList, Hashtable, Arrays etc.

3. java.io: - This package handles files and input/output related tasks.

4. java.awt (awt = abstract window toolkit): - This package helps to develop GUI (Graphical user interface). It consists of 2 important sub packages, namely: java.awt.event and java.awt.image.

5. javax.swing: - x stands for extended package. The classes in this package have been derived from other package. This package helps to develop GUI like java.awt.

6. java.net: - net stands for network17. Client/Server programming can be done using this package. It uses

TCP/IP internally.

7. java.applet: - Applets are small intelligent programs, which travel form one place to another place on internet.

8. java.sql: - sql stands for structure query language. This package helps to connect to databases like oracle and utilize them in java.

9. java.beans: - Beans are software reusable components. They can be developed using this package. 10. java.rmi: - rmi means remote method invocation18. The objects, which exist on one computer in the

network, can be invoked from another computer and can be used.

11. javax.servlet: - Servlets are server side programs which communicate several clients at a time. Servlets are server side programs, which handle clients. This package is useful to develop servlets.

 Class is model for creating objects. In case we have to write methods & variables.

 Data types represent the type data stored into variable (i.e. into memory locations).

15FONT is a class 16 BOLD is a constant

17 Network: - Interconnection of computers are called as network. 18 Invocation = Calling

(13)

Data types and literals: - A data type represents the type of data stores in memory (variable). Integer data type: - It represents integer numbers i.e. the numbers without decimal points. Subtype: -

S. No. Data type Memory size Min & Max value

1. byte 1 byte -128 to 127 2. short 2 bytes -32768 to +32767 3. int 4 bytes -2147483648 to +2147483647 4. long 8 bytes -9223372036854775808 to +9223372036854775807 (or) -9.2 x 10-18 to 9.2 x 1018

Ex: - byte r.no = 10 (0 - literal)

 Literal means the constant value being directly storing into variable. long x = 150L;

L means take that number forcibly as long integer to allot the memory as user defined.

float data types: - They can handle numbers with decimal points. Such number’s called floating data type. Sub type: -

S. No. Data type Memory size Min & Max value

1. (Single precision ) float 4 bytes -3.4e38 to + 3.4e38 2. Double precision 8 bytes -1.7e308 to + 1.7e308

Q.) What is the difference between float and double? *****

Ans: - float can represents up to 7 digits after decimal point accurately. Double can represents up to 15 digits after decimal point accurately. Ex: - float PI = 3.142F;

 F represents forcing the JVM to take the value as float because JVM defaultly takes any decimal values as double.

Character data type: - It represents a single characters.

S. No. Data type Memory Size Min & Max value

1. Char 2 bytes 0 to 65535

Ex: - char ch = ‘x’;

ASCII – American standard code for information interchange.

S. No. Data type Memory Size Min & Max value

1. char 2 bytes 0 to 65535 2. byte 1 byte -128 to 127 3. short 2 bytes -32768 to +32767 4. int 4 bytes -2147483648 to +2147483647 5. long 8 bytes -9223372036854775808 to +9223372036854775807 (or) -9.2 x 10-18 to 9.2 x 1018

6. float 4 bytes -3.4e38 to + 3.4e38

7. double 8 bytes -1.7e308 to + 1.7e308

8. boolean 1 bit 0 or 1

(14)

Q) What is Unicode? *****

Ans: - Unicode is specification that includes the alphabetic of all international languages into java character set. Unicode uses 2 bytes to represent single character.

4. String data types: - String represents a group of characters. Strings are objects of string class in java. Ex: - String name “Inet solv”;

String str = new String (“A String”);

Boolean data type: - They store either true or false. It can handle only two values. Ex: - boolean response = true;

Complete list of Java keywords:

-abstract boolean Break byte case catch

char class Const continue default do

double else Extends final finally float

for goto If implements Import instanceof

int interface Long native new package

private protected Public return short static

strictfp super Switch synchronized this throw

throws transient Try void volatile while

assert

Transient: - A value of an instance variable in a class will not persistent when the object is stored, such an instance variable can be specified as transient variable, indicating that its value need not be saved when objects of its classes are put in persistence storage or it prevents fields from ever being serialized. Transient fields are always skipped when objects are serialized.

Transient variables aren’t appropriate for equals() and hashCode() methods.

Note: - That the transient modifier cannot be specified for static variables as these do not belong to objects. Volatile: - In multithreading environment, threads might cache the values of member variable for efficiency reason. Since threads can share a variable, it is then vital that reading & writing of the value in the copies and the master variable do not result in any inconsistency. As these variables values could be changed unexpectedly. The volatile modifier can be used to inform the compiler that it should not attempt to perform optimization on the variable.

instanceOf: - The instanceof operator is used for object reference variables only, and you can use it to check whether an object is of a particular type. By type, we mean class or interface-in other words, if the object referred to by the variable on the left side of the operator passes the IS-A test for the class or interface type on the rightside. Even if the object being tested is not an actual instantiation of the class type on the right side of the operator, instanceof will still return true if the object being compared is assignment compatible with the type on the right.

class A {

public static void main (String [] args) {

String s = new String("foo"); if (s instanceof String) {

System.out.print("s is a String"); }

}

Operator: - An operator is a symbol that represents an operation. `

a + b (∴ a, b are operands, + is the operator) Operand: - An operand is a variable on which operator acts upon.

An operator may act upon a single operand. It is called unary operator. If an operator acts upon two operands is called binary operand. If an operator acts on three operands is called ternary operand. Operators in Java: -

(15)

2. Unary Operators: - - ++

--3. Assignment Operators: - = += -= *= /= %= 4. Relational Operators: - < <= > >= == != 5. Logical Operators: - && || !

6. Boolean Operators: - & | !

7. Bitwise Operator: -

a) Bitwise Compliment: - ~ b) Bitwise and: - &

c) Bitwise or: - | d) Bitwise xor: - ^

e) Bitwise left shift <<

f) Bitwise right shift >> 8. Ternary Operator (Conditional Operator): - ?:

9. Dot Operator (.):

-a) To refer a class in a package: - java.util.Date

b) To refer a method in class: - math.pow() emp.getsal() c) To refer a variable in a class: - Employee.name, emp.name 10. Instanceof Operator: - To test whether an object belongs to a class. Ex: - emp instanceof Employee.

Arithmetic Operators: - These operators perform basic arithmetic calculations like addition, subtraction, etc…

Ex: - a = 13, b = 5

S. No. Operator Meaning Example Result

1. + Addition a + b 18

2. - Subtraction a – b 8

3. * Multiplication a * b 65

4. / Division a/b 2.6

5. % Modulus operator (Remainder

of division) a% b 3

Unary Operators or Unary minus (-) Operator: - This operator negates the value of a variable. (Negation means converting – value into + value vice versa).

Ex: - int x = -5;

System.out.printlin(x); -5 System.out.printlin(-x); 5 System.out.printlin(-(-x)); -5 System.out.printlin(-(-(-x))); -5

Increment Operator (++): - This operator increases the value of a variable by one. Ex: - int x = 1;

++x 2 x++  3 x = x + 1  4

Writing ++ before a variable name is called pre incrementation. Writing ++ after a variable name is called post incrementation.

 In pre incrementation, incrementation is done first any other task is done next.

 In post incrementation any other task is done first, incrementation is done at the end.

Ex. 1: - int x = 1; int x = 1;

S.o.println(x); S.o.println(x) S.o.println(++x); S.0.println(x++); S.o.println(x); S.o.println(x); Output Output 1 1 2 1 2 2

(16)

Ex. 2: - a = 1; a = 1;

b = 2; b = 2;

a = ++b; a = b++;

a = 3 a = 2

b = 3 b = 3

Ex 3: - What is the value of the following expression, if a = 7?

++a*a++; [ b ]

a) 49 b) 64 c) 56 d) 72 e) None of these Decrement Operator (--): - This operator decreases the value of a variable by one.

int x = 1; --x  0 x--  -1 x = x – 1  - 2

Writing – before a variable is called pre decrementation, writing after a variable is called post decrementation.

Assignment Operator (=): -

1. It is used to store a value into a variable. Ex: - int x = 15;

2. It can store the value of variable into another variable. Ex: - int y = x;

3. It can store the value of an expression into a variable. Ex: - int z = x + y – 10;

Note: - At the left hand side of assignment we should use only one variable. Compact Notation: - a = a + 10  a +=10 b = b – 100  b -=10 j = k * j  j *=k i = i/10; i/=10 p = p%10  p%=10

Relational Operators: - These operators are useful to compare two quantities. They are used to constant conditions.

> < >= <= == != Ex: - if(a>b)………..;

if(a==100)……; if(x!=y)………...;

Logical Operators: - These operators are useful to combine more than one condition. Combining more than one condition called Compound condition.

&& - and || = or ! - not Ex: - if(a>b && b>c)………...;

if(a==100||b=50)…………...; if(!(x==1))………;

Boolean Operator: - These operators act upon Boolean variables and they return Boolean value. & - Boolean and

| - Boolean or boolean a = true; boolean b = false; a & b - false a & a - true b | b - false !a - false !b - true

Bitwise Operators: - These operators act upon individual bits of a number.

Convert 45 into binary: - Divide the number successively by 2 and table remainders from bottom to top. 45 0 0 1 0 1 1 0 1

22 – 1 11 – 0 5 – 1

(17)

2 – 1 1 – 0 0 – 1

Converting 00101101 into decimal: - Multiply the bits by the powers of 2 & take the sum of those products.

0 0 1 0 1 1 0 1

x x x x x x x x

27 + 26 + 25 + 24 + 23 + 22 + 21 + 20

0 + 0 + 32 + 0 + 8 + 0 + 0 + 1 = 45 Bitwise Compliment (~): - This operator gives complement from of a number.

Ex: - int x = 10; ~x = -11;

Bitwise and (&): - This operator performs anding operations on individual bits a b a & b This table is called truth table. It means, it shows 0 0 0 input and output bits

0 1 1 1 0 0 1 1 1 Ex: - x = 10 y = 11, x & y =? x = 0 0 0 0 1 0 1 0 y = 0 0 0 0 1 0 1 1 x & y = 0 0 0 0 1 0 1 0 = 10

Bitwise or (|): - This operator performs or-ing operations on individual bits

a b a | b 0 0 0 0 1 1 1 0 1 1 1 1 Ex: - x = 10 y = 11, x | y =? x = 0 0 0 0 1 0 1 0 y = 0 0 0 0 1 0 1 1 x | y = 0 0 0 0 1 0 1 1 = 11

Bitwise Xor (^): - ^ is called as Circum flex or Cap or caret. This operator performs exclusively oring operations on individual bits

a b a | b 0 0 0 0 1 1 1 0 1 1 1 0 Ex: - x = 10 y = 11, x ^ y =? x = 0 0 0 0 1 0 1 0 y = 0 0 0 0 1 0 1 1 x ^ y = 0 0 0 0 0 0 0 1 = 1

Bitwise left shift (<<): - This operator shifts the bits towards left a specified number of times. Ex: - x = 10; x << 2 =?

x = 10 0 0 0 0 1 0 1 0

x<< 2 0 0 1 0 1 0 0 0 = 40

Bitwise right shift (>>): - This operator performs shifting of bit towards right a specified number of times. x = 10; x = 10 x >>2 x >> 2 x = 10 0 0 0 0 1 0 1 0

0

- 1

- 2

- 3

- 4

1

2

3

AND gate OR gate

XOR gate

(18)

x >> 2 0 0 0 0 0 0 1 0 = 2

Bitwise zero fill right shift (>>>):

-Q) What is the difference >> and >>>? *****

Ans: - >> shifts the bits towards right and also preserves the sign bit (0 for positive and 1 for negative sign).

>>> also shifts the bits towards right but does not preserve the sign bit. It always fills the sign bit with 0. For this reason it is called zero fill right shift.

Ex: - //Bitwise operators class Bits{

public static void main (String args[ ]){ byte x,y;

x = 10;

y = 11;

System.out.println(“~x = ” +(~x)); System.out.println(“x & y” = +(x&y)); System.out.println(“x | y” = +(x|y)); System.out.println(“x ^ y” = +(x^y)); System.out.println(“x << y” = +(x<<y)); System.out.println(“x >> y” = +(x>>y));

}

}

Ternary Operator: - This operator acts on three variables i.e. it will takes three variables.

This operator works like a conditional if-else statement. So this operator is called as conditional operator. Syntax: - var = exp1?exp2:exp; max = (a>b)?a : b; (or) if(a>b) max = a; else max = b; dot (.) operator: -

1. packagename.classname (to refer classname) java.io.BufferedReader

2. classname.var or objectname.var (to refer variable) System.out emp.name

3. classname.method() or objectname.method() (to refer method)] Math.sqrt() br.read

instanceOf operator: - It is denoted as instanceof. It is used to test whether the object belongs to that class or not.

Syntax: - objectname instanceof classname Ex: - br instanceof BufferedReader

This operator returns true of false i.e Boolean values.

Executing the statements one by one by JVM is called sequential execution. In sequential execution programmers does not have better control on the flow of execution.

In Random execution the programmer can executive any statement directly or repeatedly. This gives better control for the programmer on the flow of execution.

(19)

Control Statements: - Control statements modify the flow of execution and give better control for the programmer on the flow of execution. Without control statements programmers can not able to write better programs.

1. if…else statement 4. for loop 7. continue statement 2. do….while loop 5. switch statement 8. return statement 3. while loop 6. break statement

 A loop can be executed repeatedly. A statement can be executed once only.

If…else statement: - This statement performs a task (one or more statement) depending upon whether a condition is true or not.

Syntax1: - if(condition) statement1; [else statement2;]

Ex: - //Test if a given number is +ve or –ve class Demo

{

public static void main (String args[ ]) { int x; x = -15; if(x==0) System.out.println(“It is zero”); else if(x>0)

System.out.println(“x+” “is positive”); else

System.out.println(“x+” “is negative”); } } C:\rnr\javac Demo.java↵ C:\rnr\java Demo↵ Output: - -15 is negative. Syntax 2: -if(condition1) if(condition2) if(condition3) statement1; else statement2; else statement3; else statement4;

Do…while loop: - This loop repeatedly executes a group of statements as long as a given condition is true.

 Storing starting value into the variable is called initialization. Syntax: -do

{

statements; }while(condition); Ex: - //To display numbers from 1 to 10

Class Demo {

public static void main(Static args[ ]) { int n = 1; do{ System.out.println(n+ “ ”); n++; }while(n<=10); } } C:\rnr\javac Demo.java↵

(20)

C:\rnr\java Demo↵

Output: - 1 2 3 4 5 6 7 8 9 10

While loop: - This loop repeatedly executes a group of statements as long as a condition is true. Syntax: -

while(condition) {

(statements); }

Ex: - //To display even numbers up to 10 class Demo

{

public static void main(String args[ ]) {

int i = 2; while(i<=10) {

System.out.println(i);

i = i + 2; or i +=2; [

i += is called compact notation] }

} } (or)

//To display even numbers up to 10 class Demo

{

public static void main(String args[ ]) { int i = 2; while(i<=10) { System.out.println(i +=2); } } }

Q) Do…while and while loops, which loop is efficient? *****

Ans: - While loop is efficient. Right from beginning of the execution it provides control to the programmers.

for loop: - This loop repeatedly executes a group of statements as long as a condition is true. Syntax: -

for(exp1; exp2; exp3) {

statements; }

exp1 is initialization expression,

exp2 is checking condition expression as long as the condition is true. exp3 is modifying the value of variable.

Ex: - for(int i = 1; i<=10; i++) {

System.out.println(i); }

Note: - We can write for loop without exp1 or exp2 or exp3 or any two expressions or all three expressions.

Ex: - //Demo of for loop class Demo {

(21)

{

for(int i = 1; i<=10; i++) { System.out.println(i); } } } (or) int i = 1; for( ; ; ) { System.out.println(i); i++; if(i>10)break; }

Infinite loop [for( ; ; )]: - Infinite loop is a loop, which executes forever. These are drawback of programs. It is a bad programming.

for( ; ; ) do{ while(true)

{ statements; {

statement; }while(true); statements;

} }

Note: - We can write a for loop inside another for loop. This type for loop is called Nested for loop. Ex: - for(int i = 1; i<=3; i++)

{ for(int j = 1; i<=4; j++) { statements; } }

Switch Statement: - This statement is useful to selectively execute a task from a group of available tasks. Syntax: -

switch(var) {

case value1: statement1; case value2: statement2; case value3: statement3;

case valuen: statementn; [default: default statement;] }

Ex: - //Using Switch class Demo {

public static void main(String args[ ]) { char color = ‘g’; switch(color) { case ‘r’: System.out.println(“Red”); break; case ‘g’: System.out.println(“Green”); break; case ‘b’: System.out.println(“Blue”); break; case ‘w’: System.out.println(“White”); break;

(22)

default: System,out.println(“No Color”); }

} }

Switch statement more suitable for menu driven programs.

Break: - Break is a statement, which is useful to come out from the loop. Break is useful to the come out of the switch statement. It is used in three ways.

1. To come out of a loop.

2. It is used to come out of a switch block. 3. Break is used to goto end of a block19.

Syntax: - break blockname;

Q) goto statements are not available in java why? *****

Ans: - 1. goto statements are decreases the readability of a program. 2. goto statements form infinite loops.

3. goto statements make documentation20 of program very difficult.

4. goto is not part of structured programming.

 Factorial representation of all the steps of an algorithm is a flow chart. Algorithm consists step by step to solve a program.

Ex: - //break as goto class Demo {

public static void main(String args[ ]) { boolean x = true; bl1: { bl2: { bl3: { System.out.println(“Block 3”); if(x==true) break bl2; } System.out.println(“Block 2); } Systen.out.println(“Block 1”); } System.out.println(“Out of all); } }

Continue: - This statement continues the next repetition of a loop and sub sequent statements are not executed.

Syntax: -continue; Ex: - //Continue

class Demo {

public static void main(String args[ ]) {

for(int i = 10; i<=1; i--) { if(i>5)continue; System.out.println(i); } } }

19 Block: - Block represents a group of statements written in left and right braces. 20 Documentation: - Documentation is preserving a copy of a program for future use.

(23)

C:\rnr\javac Demo.java↵ C:\rnr\java Demo↵ Output: -5 4 3 2 1 Ex: - //Continue class Demo {

public static void main(String args[ ]) {

for(int i = 10; i<=1; i--) { if(i<5)continue; System.out.println(i); } } } C:\rnr\javac Demo.java↵ C:\rnr\java Demo↵ Output: -10 9 8 7 6 5 return statement: -

1. It is used to come out of a method to the calling method. Syntax: - return;

2. return statement can return a value to the calling method. Syntax: - return x;

return y; return (x+y); Ex: - //return statement in main()

class Demo {

public static void main(String args[ ]); {

int x = 1;

System.ot.println(“Before return”); if(x==1)return;

// or we can use as here System.exit(0); in the place of above statement return; System.out.println(“After return”);

} }

[

Where in System.exit(0), System is a class name and exit is a method.]

What is the difference between System.exit(0) and System.exit(1)? ***** Ans: - System.exit(0) is represents normal termination.

System.exit(1) is represents termination with errors. Homework programs: -

(24)

1. To print odd no.’s upto 100? 2. Test whether a no. is even or odd? 3. Test whether a no. is prime or not? 4. Display a multiplication table? 5. Calculate factorial of given no.? 6. Display the stars in this below form?

* * * * * * * * * * Accepting input from Keyboard:

-Stream: - It represents flow of data from one place to another place. To move data we need stream. There are two types of streams are available.

1. Input Stream: - It receives or reads data.

2. Output Stream: - It sends or writes data to some other place.

 Streams are represented by classes in java.io.package.

 Keyboard is represented by System.in [

System is a class] System.in  InputStream obj - Keyboard

System.out  PrintStream obj - Monitor System.err  PrintStream obj - Monitor Q) What is the difference between System.out() and System.err()? ***** Ans: - System.out is used to display normal messages and results.

Ex: - System.out.println(“A normal message”); System.err is used to display error messages. Ex: - System.err.println(“Error message);

 Streams are represented by input/output devices.

 By using streams we can handle hardware components even though Input/output are channel we need not to change the stream in java program. Thus we are achieving system independent.

InputStreamReader: - InputStreamReader reads the data from keyboard.

BufferedReader: - It is one type of InputStreamReader. It is connected to InputStreamReader. It accepts the data form InputStreamReader.

1. Attach the keyboard to InputStreamReader. To create an object

Class obj = new Class()

InputStreamReader obj = new InputStreamReader(System.in); 2. Attach the InputStreamReader to BufferedReader

BufferedReader br = new BufferedReader(obj);

3. Read data from BufferedReader using read() or readLine() methods. Ex: - //Accepting a single char from Keyboard.

import java.io.*; class Input {

public static void main(String args[ ]) throws IOException21

{

//Attach the keyboard to InputStreamReader

InputStreamReader obj = new InputStreamReader(System.in); //Attach the InputStreamReader to the BufferedReader

BufferedReader br = new BufferedReader(object); //read data from BufferedReader

System.out.println(“Enter a single char: ”); Char ch = (char)br.read();

21 Exception: - It means runtime error.

InputStreamReader

BufferedReader

(25)

System.out.println(“You Entered: ”+ ch); }

}

 br.read() returns int values so we have to use (char) before the br.read() to give in char value [

Char ch = (char)br.read();]

Converting one data type to another data type is called type casting or casting. ( ) is called as casting operator.

 When we are using read() method in rare conditions we will get runtime errors, so to eliminate this error we have to use throws IOException.

 read() method cannot read more than one character. Accepting a String: -

String ch = br.readLine(); readLine takes 255 characters. Ex: - //Accepting int value

import java.io.*; class Input {

public static void main(String args[ ])throws IOException {

//create BufferedReader object to accept data from keyboard

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter int No. ”);

String str = br.readLine(); int n = Integer.parseInt(str);

//parseInt(str) is a static method in Integer class System.out.println(“Number =”+n);

} }

parseInt(str) is a Static method in a integer class Accepting a float Number from keyboard:

Same as above but in the place of int n = Integer.parseInt(str); We have to write float n = Float.parseFloat(str); (or) float n = Float.parseFloat(br.readLine());

Accepting a double float Number: -Same as above

double n= Double.parseDouble(br.readLine()); Ex: - //Accept & display Employee Details

import java.io.*; class Input {

public static void main(String args[ ]) throws IOException {

// To accept data from keyboard

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //Accept Employee Data

System.out.print(“Employee ID: ”); int id = Integer.parseInt(br.readLine)); System.out.print(“Employee sex: ”); Char sex = (char)br.read();

br.skip(2);

System.out.print(“Employee Name: ”); String Name = br.readLine();

//Display Employee Data

System.out.println(“Employee Data: ”); System.out.println(“ID :”+id);

System.out.print(“Sex :”+sex);

System.out.print(“Employee Name :”+Name); }

(26)

}

br.skip(2) is used to eliminate the enter key = \r. Because when we are using br.read () & br.readLine() it will get.

Programs:

1) Accept 2 numbers from keyboard & find the result of their addition, subtraction, multiplication, division. 2) Print even no’s between m & n

3) Print Fibonacci series (0,1,1,2,3,5,8,13,21,…) 4) Print prime no series (2, 3, 5, 7, 11, 13, 17,...) ARRAY: -

An Array represents a group of elements of same data type. We can represent several elements in a single array. There are 3 types of arrays

1. One dimensional array (1D) 2. Two dimensional array (2D)

3) Multidimensional array (3D, 4D, 5D,….)

One dimensional array: - A One dimensional array represents a single row or a single column of elements. Ex: - Marks obtained by a student in 5 subjects are: 55 64 66 74 24

Creating One dimensional array: - There are 2 ways

1. We can create 1D array by declaring & initializing it directly. Ex: - int marks[ ] = {55,23,87,34,56};

Memory allocated by JVM is

55 57 68 70 69

[0] [1] [2] [3] [4] Marks 55 = marks[0]

or Marks[ i ] where i is an integer number that indicates position of the element in the array. i is also called as index. Index represents the position of an element in the array. One dimensional array consists only one index.

float x[ ] = {1.5f, 2.of,3f}; char ch[ ] = {‘a’, ‘b’, ‘c’} ; String name[ ] = {“raj”, “kamal”, “sita”};

2) WeScan create a 1D array by using “new” operator and later we can store the elements in that array. Ex: - int marks[ ] = new int[10];

marks[0] = 50; marks[1] = 60; marks[2] = 80;

Double sal[ ] = new Double[100]; String s[ ] = new String[50]; NOTE: - arrayname.length gives size of array; Ex: - // Find total & percentage of marks

import java.io.*; class Arr1 {

public static void main(String args[ ]) throws IOException {

//To accept data from keyboard

BufferedReader br = new BufferedReader(InputStreamReader(System.in)); System.out.println(“How many subjects? ”);

int n = Integer.parseInt(br.readLine()); //Create array with size n

int marks[ ] = new int[n]; //Store marks into array for(int i=0; i<n; i++); { System.out.print(Enter marks: ”); marks[ i ] = Integer,parseInt[br.readLine(); } //Find Total int tot = 0;

(27)

System.out.println(“The array elements are: ”); for(int i = 0; i<n; i++)

{

System.out.println(marks[ i ]); tot = tot + marks[ i

}

//Display the total marks

System.out.println(“Total marks = ”+ tot); //Calculate percentage

float percent = (float) tot/n; //(float) is a cast operator System.out.println(“Percentage = ”+ percent);

} }

 By default arrays are created in C,C++ on static memory, but in java every thing is created on dynamic memory

 Only one for is enough to handle One dimensional array.

Two Dimensional Array (2D Array): - 2D array represents several rows & columns of elements. Ex: - A class students are obtained marks in 5 subjects.

Student1 – 50, 51, 52, 53, 54 Student2 – 60, 61, 62, 63, 64 Student3 – 70, 71, 72, 73, 74 Creating 2D array:

-1. We can declare and initialize directly.

Ex: - int marks[ ] [ ] = {{ 50, 51, 52, 53, 54}, {60, 61, 62, 63, 64}, {70, 71, 72, 73, 74}}; JVM allot memory for the above array like below.

C0 C1 C2 C4

1D array is a combinations of several 1D array marks[ i ] [ j ]

In this i and j are indexes. i represents as row position and j represents as column position. 2D array consists 2 indexes.

Ex: - float marks[ ] [ ] = {{ 1.1f, 1.2f, 1.3f, 1.4f, 1.5f}, {2.1f, 2.2f, 2.3f, 2.4f, 2.5f}, {3.1f, 3.2f, 3.3f, 3.4f, 3.5f}};

2. We create 2D array using new operator and we can store elements in to it. int marks [ ] = new int[3] [5];

char ch[ ] = new char[100] [100]; Ex: - // To display a 2D array in a matrix

Class Arr1 {

public static void main(String args[ ]) {

float marks[ ] [ ] = {{ 1.1f, 1.2f, 1.3f, 1.4f, 1.5f}, {2.1f, 2.2f, 2.3f, 2.4f, 2.5f}, {3.1f, 3.2f, 3.3f, 3.4f, 3.5f}}; System.out.printl(“In matrix form: ”);

for(int i = 0; i<3; i++) { for(int j = 0; j<4; j++) { System.out.println(x[ i ] [ j ] + “\t”); } System.out.println(); } }

r

1

r

2

r

3

(28)

}

 The outer most for loop represents row of matrix and inner most for loop represents column of matrix.

for this matrix to find total of matrix same as above and then add below program float tot = 0;

for(int i = 0; i<3; i++) {

for(int j = 0; j<4; j++) {

tot = tot + [ i ] + [ j ]; }

(

Parameter is useful to receive values from outside to the main method.) C:\>java prog 10 11 12

Command line

10 - args[0] 10 - Command line argument 11 - args[1]

12 - arg[s2]

Command line arguments are stored in args[0], args[1], args[2].

Command line arguments are the values passed to the main method at the time of running a program.

Ex: - //Program finds args length class Args

{

public static void main(String args[ ]) {

//find no. of args. int n = args.length;

System.out.println(“No. of args = “ +n); //Displays args

for(int i = 0; i<n; i++)

System.out.println([args[ i ]); }

}

13. Add two matrices (or 2D arrays) and display their sum of matrix. Also display the total of their elements.

14. Find the transpose of given matrix.

What are differences between Array and Vector:

-Array Vector

1. The size of the array needs to be declared in an advance. An array is denoted as [ ]

1. No need to declare the size of vector. We may give its size or you may not.

2. Once declared array can’t grow in size. 2. Vector can always grow in size if we start adding more elements to it then its size will grow.

3. Array can store primitive data types like int, char, float, double ….

3. Storing the primitive data types is not possible in case of Vector. It can store only object references. 4. Array is not synchronized. 4. Vector is synchronized.

Why do you want to convert a collection into an Array: -1. To obtain faster processing time for certain operation.

2. To pass an array to a method that is not overloaded to accept a collection.

(29)

String: - A string represents a group of characters. A string means character array in C-Language, but a string doesn’t means character array. A string represents an object of string class. String class is created in java.lang package. String class is declared as final class. String class can not extend another class.

String class provides the following functionality for handling Strings: -1. Creating and initializing String.

2. Reading individual characters in a String. 3. Comparing Strings.

4. Changing the case of characters in a string (toUpperCase/toLowerCase) 5. Concatenating String.

6. Searching for characters and sub Strings 7. Extracting sub strings

8. Conversion of objects to Strings.

Creating String class object: -

1. We can create a string by directly storing a string into string class object. String str = “Hello”;

Where as String is a class name

str is object name (referring the memory) 2. We can create a string object using new operator.

String str = new String(“Hello”); 3. We can create a string from a character array

char arr[ ] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’}; String str = new String(arr); String str = new String(arr, 1, 3); Here 1 represents the 1st character

3 represents No. of characters.

All will be displayed writing string like above.

java.lang.String: - In String class methods available as below. 1. String concat (String str): -

Concatenates22 the calling string with str.

Note: - + will also do the same

String s1 = “Hydera”; String s2 = “bad”; String x = s1.contact(s2); ‘+’ is called as concatenation operator. 2. int length: - returns the length of a string.

int n = s1.length();

3. char charAt(int index): - It receives the integer number and returns the character at the specified. s1.charAt(2)

4. int compareTo(String str): - returns a negative value if the string comes before str. in dictionary order. A positive value if the string comes after str, or 0 if the strings are equal.

Ex: - String s1 = “Boy”; String s2 = “Box”;

Here ASCII value of B = 66, o = 109, x = 118, y = 119 s1 = Boy = 66 109 119

s2 = Box = 66 109 118 0 0 1 Here Output is 1

int n = s1. compareTo(s2); When s1< s2 it will gives negative

s1> s2 it will gives positive s1= s2 it will gives 0

It compare with dictionary form, i.e. which strings comes first & next.

(30)

What is the difference between compareTo() method and equals() method? *****

Ans: - compareTo() method returns the int data type, where are equals() method returns the boolean data type.

S. No. Capital Alphabates

ASCII Code Small Alphabates

ASCII Code Numeric Numbers ASCII Code 1. A 65 a 95 0 48 2. B 66 b 96 1 49 3. C 67 c 97 2 50 4. D 68 d 98 3 51 5. E 69 e 99 4 52 6. F 70 f 100 5 53 7. G 71 g 101 6 54 8. H 72 h 102 7 55 9. I 73 i 103 8 56 10. J 74 j 104 9 57 11. K 75 k 105 10 58 12. L 76 l 106 11 59 13. M 77 m 107 12 60 14. N 78 n 108 13 61 15. O 79 o 109 14 62 16. P 80 p 110 15 63 17. Q 81 q 111 16 64 18. R 82 r 112 17 65 19. S 83 s 113 18 66 20. T 84 t 114 19 67 21. U 85 u 115 20 68 22. V 86 v 116 21 69 23. W 87 w 117 22 70 24. X 88 x 118 23 71 25. Y 89 y 119 24 72 26. Z 90 z 120 25 73

5. int compareToIgnoreCase(String str): - returns a negative value if the string comes before str. in dictionary order. A positive value if the string comes after str, or 0 if the strings are equal. It ignores the uppercase or lowercase.

6. boolean equals(String str): - returns true if the string equals str. It is a case sensitive comparison.

7. boolean equalsIgnoreCase(String str): - returns true if the string equals str. This case insensitive comparison.

8. boolean startsWith(String prefix): - returns true if the string starts with prefix. 9. boolean endsWith(String suffix): - returns true if the string starts with suffix. Note: - Above two methods use case sensitive comparison.

str.startsWith(“This”); --- true str.endsWith(“book”); --- true 10. int indexOf(String str): - return the first occurrence of str in the string.

References

Related documents

Your final grade shall be based upon three components: your class participation (20%), your class presentation (30%), and your final paper (50%). Your final paper is to be

public class XorSocket extends Socket { private final byte pattern;}. private InputStream in

We have proposed a computational model for a reach-to-grasp movement, where the state of the hand is estimated and predicted by Kalman filters, and a motor command is generated

1) Class participation (20% of the final grade). Participation will be measured by involvement in class discussions and the completion of in-class assignments. You must attend

It is the intention of the Im- proving Chronic Disease Veri fication and Medication Access in the Chicago Public Schools initiative to ultimately use these findings to improve the

` The scope management plan is a document that includes descriptions of how the team will prepare the project scope statement, create the WBS, verify completion of the

Vision loss is often considered separate and even distant from other age-related chronic conditions, such as de- pression, osteoporosis, and dementia, which all impact on

The final grade will be based on class participation and attendance, online quizzes, problem sets, a midterm exam, and a final exam, with the following weights:.. Class