O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

JavaClassPresentation

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Carregando em…3
×

Confira estes a seguir

1 de 72 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Semelhante a JavaClassPresentation (20)

Anúncio

Mais recentes (20)

JavaClassPresentation

  1. 1. James Gosling Welcome To Programming in JAVA By Mr. A. Julias Ceasor Bosco Institute of Information Technology
  2. 2. After this unit will be over, you will be the Know-how of the followings: Java Basics: OOP and Java - Objects and Classes – Encapsulation - Inheritance - Polymorphism - Java Language - The Primaries - Character Set - Tokens - Constants - Variables - Operators and Expressions - Library Methods - Strings - I/O Streams - Formatting the Output values - Control Statements – If - Switch - While - Do-While-for.
  3. 3. Java Fundamentals & Basics for Programming What is Java? Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++ and enforces an object-oriented programming model. Key Concept of Java: • Java Technology is: - Simple, Secure, Robust, Complete Object Oriented and Platform Independent High level Language. - It is portable and Multi-thread technology gives High performance. • It is based on concept called JVM. - Act as a translator between the language and the underlying Software and Hardware.
  4. 4. What is Object Oriented Programming? • This is a technique used to develop programs revolving around the real world entities. • In OOPs programming model, programs are developed around data rather than actions and logics. • In OOPs, every real life object has properties and behavior. • It contains properties (variables of some type) and behavior (methods). • OOPs provides a better flexibility and compatibility for developing large applications. What is object? • Object is a real world entity. • the Real world Objects are: Building, Objects Car, Fruit,… and etc.
  5. 5. Attributes: • Four Wheels • Engine • Seats An Object • Steering • Speed • Disk Break • Etc. Functionalities (Methods): +Wheels for Rolling Car + Engine for Moving +Seats for Sitting +Break for Control +Etc.
  6. 6. Programming Object: - It is combination of Data and Methods. An Object Attributes of an object Method Method (-) Functionalitie s of an Object Data (+) Method Method Object = Data + Methods
  7. 7. Pillars of OOPL: OOPL PolymorphismDynamic Binding Inheritance Encapsulation
  8. 8. Why the Java? • C, C++ and other programming languages are not flexible for complex problems. • Other languages are Structured and Object Oriented Programming language. Not Fully OOPL. • Others are not Platform Independent. Evolution of Java • In 1990, the group of engineers developed a software for consumer electronics at Sun micro System of USA. • This group is headed by James Gosling. • In 1991, it is proved that it satisfy the concepts of OOPL like C++ and called as 'Oak' by James Gosling. • In 1992, the Green Project is started. • In 1993, the team developed small applet program for World Wide Web. • In 1994, the team came up with browser called HotJava. • In 1995, the 'Oak' renamed as 'Java'
  9. 9. Why is it named 'Oak'? When the 'Ever green' team was Developed Software for consumer Electronics, such as Set-Top-Boxes, and Other hand held devices, the Head of the team James Gosling saw a Oak tree in front of his office. The Oak tree is a ever green tree and never its leaves get dry. Due to this reason, the software named as 'Oak'.
  10. 10. Features of Java: • Java is:  simple  easy to design  easy to write  and therefore easy to compile  debug  and learn than any other programming languages. • Java is object-oriented, that is used to build modular programs and reusable code in other application. • Java is platform-independent and flexible in nature. • The most significant feature of Java is to run a program easily from one computer system to another.
  11. 11. Continued….. • Java works on distributed environment. • Java is secure. The Java language, compiler, interpreter and runtime environment are securable . • Java is robust. Robust means reliability. • Java emphasis on checking for possible errors. • Java supports multithreaded. Multithreaded is the path of execution for a program to perform several tasks simultaneously within a program.
  12. 12. Java Platform: • Platform is cross-combination of hardware or software environment in which a program runs. Environment Operates and for Java Controls H/W Development Java Platform Software (OS) Platform Hardware Platform
  13. 13. Java Platform: • Java Platform has Two Components. 1. Java Virtual Machine (JVM) 2. Java Application Programming Interface (API) JVM API
  14. 14. JVM: The Java Virtual Machine is the root for the Java platform and is integrated into various hardware-based platforms. API: The API is a vast collection of various software components that provide you many useful functionality to the application. It is grouped into logical collection of related classes and interfaces; these logical collection are known as packages.
  15. 15. How it Works: •All source code is written in text files (Notepad Editor) save with the .java extension • The source files are compiled into .class files by the java compiler. A .class file contains byte codes • The java launcher tool runs your application with an instance of the Java Virtual Machine.
  16. 16. Execution of Program as Platform Independent
  17. 17. A simple Java Program: HelloWorld.java import java.io.*; class HelloWorld { public static void main(String args[]) { System.out.println("HelloWorld"); } } Output: HelloWorld
  18. 18. Procedure for developing java application 1. Write a java source code as a text file (can create in notepad) using any of the text editor. • Save the file with .java extension in your directory. • The filename should be the class name of the program. • Open the command prompt to run the application • Compile the code with command javac filename.java • Run the class file with the command java filename • The output will be displayed on your console.
  19. 19. Two ways of using Java Java Source Code Applet Type Application Java Compiler Type Java Enabled Java Web Interpreter Browser Output Output
  20. 20. Java Technology: On full implementation of the Java platform gives you the following features: JDK Tools: The JDK tools provide compiling, Interpreter, running, monitoring, debugging, and documenting your applications. The main tools used are the Javac compiler, the java launcher, and the javadoc documentation tool. Application Programming Interface (API): The API provides the core functionality of the Java programming language. Deployment Technologies: The JDK software provides two type of deployment technology such as the Java Web Start software and Java Plug- In software for deploying your applications to end users. Graphical User Interface Toolkits: The Swing and Java 2D toolkits provide us the feature of Graphical User Interfaces (GUIs). Integrated Libraries: Integrated with various libraries such as the Java IDL API, JDBC API, Java Naming and Directory Interface TM ("J.N.D.I.") API, Java RMI, and Java Remote Method Invocation over Internet.
  21. 21. Structure of Java Program A set of comment lines giving the name Documentation Section of the program, author and other details. /**…….*/ or // or /*…..*/ Package Statements Declare the package names and inform the compiler the class defined below belongs to Statements e.g.: package Import this packages. student;the interpreter to load the test Instruct class contained in Student package. E.g. Interface Statements import student.test; Includes a group of methods declarations. Class Definitions Can have multiple class declarations. Main Method Class { Main method Definition Creates objects of various classes and } establishes communication between
  22. 22. Java Virtual Machine: • All language compiler translate source code into machine code for specific computer. • Java compiler produces an intermediate code known as bytecode for a machine that does not exist. • This machine is called Java Virtual Machine (JVM) • It is simulated computer with in a computer does all major functions. • the bytecode is called as virtual machine code. • this is not machine specific. • Machine specific code is generated by Java Interpreter by acting as intermediary between the virtual machine and real machine. • Illustrated below. Process of Compilation: Java Virtual Program Machine Source code Bytecode Java Compiler
  23. 23. Process of Converting bytecode into machine code Machine Code Bytecode Virtual Machine Java Real Interpreter Machine
  24. 24. Classes and Objects: Class: A class is a programming language construct that is used as a blueprint to create objects. This blueprint describes the state and behavior that the created objects all share. E.g.: Bicycles • There may be thousands of other bicycles in existence, all of the same make and model. • Each bicycle was built from the same set of blueprints and therefore contains the same components. • In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. • A class is the blueprint from which individual objects are created.
  25. 25. The following Bicycle class is one possible implementation of a bicycle: class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; }
  26. 26. Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods: class BicycleDemo { • The fields cadence, public static void main(String[] args) { speed, and gear represent the object's // Create two different Bicycle objects state, and the methods Bicycle bike1 = new Bicycle(); (changeCadence, Bicycle bike2 = new Bicycle(); changeGear, speedUp etc.) define its // Invoke methods on those objects interaction with the bike1.changeCadence(50); outside world. bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); • It is just the blueprint for bicycles that might be bike2.changeCadence(40); used in an application bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } } The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles: cadence:50 speed:10 gear:2 cadence:40 speed:20
  27. 27. Object: Object is the basic entity of object oriented programming language. Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class.  E.g.: Bicycle • Real-world objects share two characteristics: They all have state and behavior. • Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). • Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). • Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. • Ask yourself: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations.
  28. 28. • An object stores its state in fields (variables in some programming languages) • And exposes its behavior through methods (functions in some programming languages). A Software Object Data Encapsulation: Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
  29. 29. Bundling code into individual software objects provides a number of benefits, including: Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement.
  30. 30. Main Pillars of OOP: Encapsulation: • Abstraction: Hiding the information (Complexities) to the end users. E.g.: User Driving a Car. • Encapsulation is the process of binding together the methods and data variables as a single entity. • It keeps both the data and functionality code safe from the outside world. • It hides the data within the class and makes it available only through the methods. • Java provides different accessibility scopes (public, protected, private ,default) to hide the data from outside. Example: Here we create a class "Check" which has a variable "amount" to store the current amount. To manipulate this variable we create a methods and to set the value of amount we create setAmount() method and to get the value of amount we create getAmount() method .
  31. 31. class Check{ private int amount=0; public int getAmount(){ return amount; } public void setAmount(int amt){ amount=amt; } } public class Mainclass{ public static void main(String[] args){ int amt=0; Check obj= new Check(); obj.setAmount(200); amt=obj.getAmount(); System.out.println("Your current amount is :"+amt); } } Here the data variable "amount" and methods setAmount() and getAmount() are enclosed together with in a single entity called the "Check" class.
  32. 32. Inheritance: • Inheritance allows a class (subclass) to acquire the properties and behavior of another class (superclass). • In java, a class can inherit only one class (superclass) at a time but a class can have any number of subclasses. • It helps to reuse, customize and enhance the existing code. • So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class. Class A Class B inherits Fun 1 the property of class A Extends Class B Fun 2
  33. 33. class A{ public void fun1(int x){ System.out.println("Int in A is :" + x); } } class B extends A{ public void fun2(int x,int y){ fun1(6); // prints "int in A" System.out.println("Int in B is :" + x+" and "+y); } } public class inherit{ public static void main(String[] args){ B obj= new B(); obj.fun2(2,6); } } In the above example, class B extends class A and so acquires properties and behavior of class A. So we can call method of A in class B.
  34. 34. Polymorphism : • Polymorphism allows one interface to be used for a set of actions i.e. one name may refer to different functionality. • Polymorphism allows a object to accept different requests of a client (it then properly interprets the request like choosing appropriate method) and responds according to the current state of the runtime system, all without bothering the user. There are two types of polymorphism : 1.Compile-time polymorphism (Method Overloading) 2.Runtime Polymorphism (Method Overriding) Method Overloading: • In compiletime Polymorphism, method to be invoked is determined at the compile time. • Compile time polymorphism is supported through the method overloading concept in java. • Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).
  35. 35. Method Overloading (Compile-time polymorphism) class A{ public void fun1(int x){ System.out.println("The value of class A is : " + x); } public void fun1(int x,int y){ System.out.println("The value of class B is : " + x + " and " + y); } } public class polyone{ public static void main(String[] args){ A obj=new A(); // Here compiler decides that fun1(int) is to be called and "int" will be printed. obj.fun1(2); // Here compiler decides that fun1(int,int)is to be called and "int and int" will be printed. obj.fun1(2,3); } }
  36. 36. Method Overriding: • In Run-time polymorphism, the method to be invoked is determined at the run time. • The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.
  37. 37. Method Overriding (Run-time Polymorphism) class A{ public void fun1(int x){ System.out.println("int in Class A is : "+ x); } } class B extends A{ public void fun1(int x){ System.out.println("int in Class B is : "+ x); } } public class polytwo{ public static void main(String[] args){ A obj; obj= new A(); // line 1 obj.fun1(2); // line 2 (prints "int in Class A is : 2") obj=new B(); // line 3 obj.fun1(5); // line 4 (prints ""int in Class B is : 5") }
  38. 38. Character Set in Java: • The smallest units of java languages are Characters used to write Java Tokens. • These characters are defined by Unicode Character set. • The Unicode is a 16-bit character coding system. • It supports more than 34,000 characters in worldwide. • ASCII characters are subset of UNICODE Character set. lower-case <= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z upper-case <= A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V| W|X|Y|Z alphabetic <= lower-case | upper-case numeric <= 0|1|2|3|4|5|6|7|8|9 alphanumeric <= alphabetic | numeric special <= !|%|^|&|*|(|)|-|+|=|{|}|||~|[|]||;|'|:|"|<|>|?|,|.|/|#|@|`|_ graphic <= alphanumeric | special
  39. 39. Java Tokens: •Smallest individual units in a program are known as tokens. •The compiler recognizes them for building up expressions and statements. •Java language includes Five types of tokens. They are: •Reserved Keywords •Identifiers •Literals •Operators •Separators
  40. 40. Keywords: •Keyword are an essential part of a language definition. •Java has 50 keywords listed below. •Keywords have specific meaning in Java. •We cannot use them as names for variables, classes, methods and so on. • All keywords are to be written in lower-case letters. •It is good practice avoiding usage of key words as identifiers. •keywords are case-sensitive.
  41. 41. List of Keywords in Java abstract continue goto package switch assert default if private this boolean do implements protected throw break double import public throws byte Else Instanceof Return Transient Case Extends Int Short Try Catch Final Interface Static Void Char Finally Long Strictfp Volatile Class Float Native Super While Const For New Synchronized enum
  42. 42. Identifiers: •Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. •Rules for Identifiers: 1. They can have alphabets, digits, underscore and dollar sign characters. • They must not begin with digit. • Uppercase and lowercase letters are distinct. • They can be of any length. Literals: Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables.
  43. 43. Java specifies Five major types of literals. They are: • Integer Literals E.g.: 123 • Floating-point Literals E.g.: 123.45 • Character Literals E.g.: 'X' or 'x' • String Literals E.g.: "Hello" • Boolean Literals E.g.: true or false Operators: An operator is a symbol that takes one or more arguments and operates on them to produce a result. Separators: Separators are symbols used to indicate where groups of code are divided and arranged.
  44. 44. separators Note that the first three separators are tokens that separate/punctuate other tokens. The last six separators (3-pairs of 2 each) are also known as delimiters. For example the Java code Math.max(count,limit); contains nine ; , . ( ) { } [ ] tokens. • An identifier (math), followed by • A separator (a period), followed by • Another identifier (max), followed by • A separator (the left parenthesis delimiter), followed by • An identfier (count), followed by • A separator (a comma), followed by • Another identifier(limit), followed by • A separator (the right parenthesis delimiter), followed by • A separator (a semicolon)
  45. 45. Java Statements Expression Statements Labeled Statements Control Synchronize Statements Guarding Statements St. Selection Iteration Jump Statements Statements Statements break return if switch continue If- else while do for
  46. 46. Constants: Definition: Constants in Java refer to fixed values that do not change during the execution of a program. Java Constants Java Constants Java Constants Integer Real Character String Constants Constants Constants Constants Decimal : 123 E.g.: Fractional : 0.0065,-0.75 E.g.: Octal : 037 "Hello" "1223" Exponential : 1.5e+5 '5' 'X' ';' Hexadecimal: 0X9F
  47. 47. Integer Constants: An integer constant refers to a sequence of digits. Real Constant: A constant which has fractional part is called Real constant. Character Constant: A single character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. String Constant: A string constant is a sequence of characters enclosed between double quotes. Backslash Character Constants: 'b', 'f', 'n', 'r', 't', '"', '"', ''
  48. 48. Variables: A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program. Rules for variable names: 1. They must not begin with a digit. • Uppercase and lowercase are distinct. • It shou8ld not be a keyword. • White space is not allowed. • Variable names can be of any length. Declaration of variables: Variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. type variable1, variable2, …………, variableN; Declaration does : 1. Tell the compiler what the variable name is. • Specify what type of data the variable will hold. • Decides the scope of variable (depends on the place it is declared).
  49. 49. Scope of Variables: The area of the program where the variable is accessible is called its scope. It is classified into three kinds: • Instance variable • Class variable • Local variable Instance: Instance variable is declared inside the class. It is created when the objects are instantiated and therefore they are associated with the objects. They take different values for different object. Class: It is also declared inside the class and it is global variable to a class and belong to the entire set of objects that creates. Only one memory location is created for each class. Local: Variables declared and used inside methods are called local variables. And it also can be declared inside the block of codes that defined between { and }.
  50. 50. Data Types in Java: • Data types specify the size and type of values that can be stored. • Variety of data types available allow the programmer to select the type appropriate to the needs of the application. DATA TYPES IN JAVA Primitive Non-Primitive (Intrinsic) (Derived) Numeric Non-Numeric Classes Arrays IntegerFloating- Character Boolean Interface Point
  51. 51. Integer Type: • Can hold whole numbers such as 123, -234. • It has Four types of Integer Types: o Byte o Short o Int o Long Floating Point Types: • Can hold numbers containing fractional parts such as 57.78 and -45.78. • It has two types of values: o Single Precision o Double precision
  52. 52. Character Type: • To store character constant in memory the data type Char is used. • It assumes a size of 2 bytes and holds a single character. Boolean type: this type of data type is used to hold the values of Boolean such as ‘true’ or ‘false’. Symbolic Constants: Storing of some Constant value (which is needed frequently in the program) to a symbol is called Symbolic Constant. final type symbolic-name = value; E.g.: final int STRENGTH = 100; Type Casting: The process of Converting one data type to another is called casting. type variable1 = (type) variable2;
  53. 53. Operators: Operators are used in programs to manipulate data and variables. The list of Operators: 1. Arithmetic operators • Relational operators • Logical operators • Assignment operators • Increment and decrement operators • Conditional operators • Bitwise operators • Special operators
  54. 54. Arithmetic Operators Operator Meaning < + Is less than Addition or unary plus <= Is less than or equal to - Subtraction or unary minus > Is greater than * Multiplication >= Is greater than or equal to / == Division Is equal to Relational Operators != % Moduloequal to Is not division
  55. 55. Logical Operators Operator Meaning ++ = && Incrementing value Store value Logical AND -- || Decrementing value Logical OR ! Assignment Operator Logical NOT Increment and decrement Operators Conditional Operator Exp1 ? Exp2 : exp3
  56. 56. Bitwise Operators Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ One's complement << Shift left >> Shift right >>> Special Operators zero fill Shift right with Instanceof Operator: E.g.: person instanceof student Dot Operator: E.g.: person.age
  57. 57. postfix [] . () expr++ expr– unary ++expr –expr +expr -expr ! ~ creation/caste new (type)expr multiplicative */% additive +- shift >> >>> relational < <= > >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || ternary ?: assignment = “op=” Operator Precedence
  58. 58. Control Statements: There are two types of control statements. They are: 1. Decision making and Branching Statements • Decision making and Looping statements Decision making and Branching: •when a program breaks the sequential flow and jumps to another part of the code, it is called branching. •When the branching is based on a particular condition, it is known as conditional branching. •If branching takes place without any decision, it is known as unconditional branching. They are: 1. If statement • Switch statement • Conditional operator statement
  59. 59. If Statement: The four forms of If statement: 1. Simple if • If….else • Nested if…else • Else if ladder Simple if: Entry General form: if (test expression) true { Test ? statement-block; } Statements block False statement-X; Statements X Next statements
  60. 60. If…Else statement: Entry General form: if (test expression) False Test true { True-block statement; ? } Statements block False Statements block else { False-block statement; Statements X } statement-X; Next statements Conditional Operator: General form: Conditional expression ? Expression-1 : Expression-2
  61. 61. Nested If…Else statement: General form: if (test expression) { if (test expression) Entry { True-block statement; False Test true } ? else { Statements block False Test true False-block statement; False ? } } Statements Statements else { False-block statement; } Statements X statement-X;
  62. 62. Else…If Ladder: General form: Entry if (test expression) else if (test expression) False Test true Statement-1; else if (test expression) ? Statement-2; Statements block False else False Test true Default St; ? Statement-X; Statements Test False ? Statements true Default Statements X
  63. 63. Switch Statement: General form: Switch (expression) { case value-1: blockt-1; break; case value-1: blockt-1; break; default: default-block; break; } Statement-X;
  64. 64. Loop Controls: There are three types of looping statements: 1. While construct • Do construct • For construct A looping process, in general, would include the following four steps: 1. Setting and initialization of a counter • Execution of the statements in the loop • Test for a specified condition for execution of the loop • Incrementing the counter
  65. 65. Loop control structures: Entry Entry False Test ? Body of the loop true true Body of the loop Test ? False Entry control Exit control
  66. 66. The While Statement: The for Statement: Entry Controlled Loop. Another entry Controlled Loop. General Form: General Form: Initialization; for (initialization; test-condition; While (test-condition) increment) { { Body of the loop; Body of the loop; } } The do Statement: Nesting of for Loops: Exit Controlled Loop. General Form: General Form: for (initialization; test-condition; Initialization; increment) do { { for (initialization; test-condition; Body of the loop; increment) } { While (test-condition); Body of the loop; } }
  67. 67. Jump in Loops: Skipping a Part of a Loop: During the loop operations, it may Java permits a jump from one be necessary to skip a part of the statement to the end or beginning body of the loop under certain of a loop as well as out of loop. conditions. Jumping Out of Loop: the continue statement causes the General Form: loop to be continued with the next Initialization; iteration after skipping. While (test-condition) General Form: { …………. Initialization; …………. While (test-condition) if (condition) { …………. break; …………. Body of the loop; } Exit from loop if (condition) continue; …………….. Body of the loop; Skip the …………….. } iteration …………….. ……………..
  68. 68. Labeled Loops: General Form: Outer: While (test-condition) { …………. …………. if (condition) Body of the loop; Transferring continue Outer; } Control …………….. ……………..
  69. 69. Java Library Methods: Strings: In Java string is a sequence of characters. Java implements strings as objects of type String. String Constructors: String(char chars[]) String(char chars[], int startindex, int numChars) String(String strObj) Strin(byte asciiChars[]) String(byte asciiChars[], int startIndex, int numChars) Where: startIndex • specify the subrange begins and numChars • specify the number of characters to use. Declaration: E.g.: String S = new String();
  70. 70. Methods in String Description int length() Return the length of the string String toString() Converts data into string representation Char charAt(int where) Returns a character at index specified Void getChars(int sourceStart, Extract the specified characters from one string int sourceEnd, char target[], int to another targetStart) char[] toCharArray() Returns an array of characters boolean equals(Object str) Returns boolean value Boolean startsWith(String str) Returns boolean value Boolean endsWith(String str) Returns boolean value int compareTo(String str) If value is: < 0 • Invoking String is less than str > 0 • Invoking String is greater than str == 0 • Invoking String equal to str String substring(int Separate the substring from main string startIndex,int endIndex) String concat(String str) Concatenation of two strings String replace(char original, Replace the string char replace) String trim() Remove the white space in a string.
  71. 71. Methods in String Description Static String value(double Converts data into human readable format num) String toLowerCase() Converts letters to lower case String to UpperCase() Converts letters to Uppercase Char charAt(int where) Return a character Void setCharAt(int where, Set the character at its position char ch) StringBuffer delete(int start,Delete the content at specified position. int end) and StringBuffer deleteCharAt(int where) StringBuffer replace(int Replace the string at specified positions start, int end, String str) '+' is a Concatenation It just join the strings or data operator of Strings or any Data types.

×