Java programming notes

August 17, 2017 | Autor: Santosh Lamsal | Categoria: Java Programming
Share Embed


Descrição do Produto

Lexical Structure
The lexical structure of a programming language is the set of elementary rules that define what are the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what is punctuation, reserved words, identifiers, constants and operators. Some of the basic rules for Java are:

Java is case sensitive.
Whitespace, tabs, and newline characters are ignored except when part of string constants. They can be added as needed for readability.
Comments in java are used for documentation, but they don't change code execution.
Statements terminate in semicolons! Make sure to always terminate statements with a semicolon.
Commas are used to separate words in a list
Round brackets are used for operator precedence and argument lists.
Square brackets are used for arrays and square bracket notation.
Curly or brace brackets are used for blocks.
Keywords are reserved words that have special meanings within the language syntax.
Identifiers are names for constants, variables, functions, properties, methods and objects. The first character must be a letter, underscore or dollar sign. Following characters can also include digits. Letters are A to Z, a to z, and Unicode characters above hex 00C0. Java styling uses initial capital letter on object identifiers, uppercase for constant ids and lowercase for property, method and variable ids.

Note: an identifier must NOT be any word on the Java Reserved Word List

Data Types
Limits and Size of the primary data types

byte:
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
Example: byte a = 100 , byte b = -50

short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000

int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
int is generally used as the default data type for integral values unless there is a concern about memory.
The default value is 0.
Example: int a = 100000, int b = -200000

long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, int b = -200000L

float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally the default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4

boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true

char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'

Literal Constants
A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point), character, boolean or string values.
Example of literals:
Integer literals:
33 0 -9
Floating-point literals:
.3 0.3 3.14
Character literals:
'(' 'R' 'r' '{'

Boolean literals:(predefined values)
true false
String literals:
"language" "0.2" "r" ""
Note: Three reserved identifiers are used as predefined literals:
true and false representing boolean values.
null representing the null reference.

Let's have a closer look at our literals and type of data they can represent:
Integer Literals
Integer data types consist of the following primitive data types: int,long, byte, and short.
int is the default data type of an integer literal.
An integer literal, let's say 3000, can be specified as long by appending the suffix L (or l) to the integer value: so 3000L (or 3000l) is interpreted as a long literal.
There is no suffix to specify short and byte literals directly; 3000S , 3000B, 3000s, 3000b

Floating-point Literals
Floating-point data consist of float and double types.
The default data type of floating-point literals is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.

We can also specify a floating-point literal in scientific notation using Exponent (short E or e), for instance: the double literal 0.0314E2 is interpreted as
0.0314 *10² (i.e 3.14).

Examples of double literals:
0.0 0.0D 0d
0.7 7D .7d
9.0 9. 9D
6.3E-2 6.3E-2D 63e-1

Examples of float literals:
0.0f 0f 7F .7f
9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f
Note: The decimal point and the exponent are both optional and at least one digit must be specified.

Boolean Literals
As mentioned before, true and false are reserved literals representing the truth-values true and false respectively. Boolean literals fall under the primitive data type: boolean.

Character Literals
Character literals have the primitive data type character. A character is quoted in single quote (').
Note: Characters in Java are represented by the 16-bit Unicode character set.

String Literals
A string literal is a sequence of characters which has to be double-quoted (") and occur on a single line.
Examples of string literals:
"false or true"
"result = 0.01"
"a"
"Java is an artificial language"
String literals are objects of the class String, so all string literals have the type String.

Variables and Arrays
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:

type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

There are three kinds of variables in Java:
Local variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor or block.
Local variables are implemented at stack level internally.
There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

Instance variables
Instance variables are declared in a class, but outside a method, constructor or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.

Class/static variables
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.

Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way.
or double myList[]; // works but not preferred way.

Operators and Expressions
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators

The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder B % A will give 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19

The Relational Operators:
There are following relational operators supported by Java language
Operator Description
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

Loops and Switches
There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example:

public class Test {

public static void main(String args[]) {
int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax:
Do{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false. Example:

public class Test {
public static void main(String args[])
{
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:

The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.A for loop is useful when you know how many times a task is to be repeated.
Syntax:
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates. Example:

public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

Enhanced for loop in Java:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays. Syntax:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. Example:

public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. The syntax of a break is a single statement inside any loop. Syntax: break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:

The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
The syntax of a continue is a single statement inside any loop:
Syntax: continue;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

Switch
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}

Command Line Arguments
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

public class Echo {
public static void main (String[] args) {
for (String s: args)
{ System.out.println(s);
}

}
}

/////////////////-------------String utilites---------------------///////////////////
public class TestOnly {
public static void main(String[]args){
String name="Ram Bahadur Thapa";
String firstName=name.substring(0, 3);
String middleName=name.substring(name.indexOf("B"),
name.indexOf("r")+1);
int haPos=name.indexOf("ha");
System.out.println(firstName);
System.out.println(middleName);
System.out.println(haPos);
}


///////////--------------Type Wrappers---------------------------////////////
A primitive wrapper class in the Java is one of eight classes provided in the java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper classes in Java are immutable. J2SE 5.0 introduced autoboxing of primitive types into their wrapper object, and automatic unboxing of the wrapper objects into their primitive value—the implicit conversion between the wrapper objects and primitive values.
Primitive type Wrapper class Constructor Arguments:
byte Byte byte or String
short Short short or String
int Integer int or String
long Long long or String
float Float float, double or String
double Double double or String
char Character char
boolean Boolean boolean or String


//////////---------------System Class & Math Class------------------////////

---------------------Math---------------------
The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
public class MathLibraryExample {
public static void main(String[] args) {
int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;
System.out.println("i is " + i);
System.out.println("j is " + j);
System.out.println("x is " + x);
System.out.println("y is " + y);
System.out.println(x + " is approximately " + Math.round(x));
System.out.println(y + " is approximately " + Math.round(y));


// Comparison operators
// min() returns the smaller of the two arguments you pass it
System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j));
System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y));
System.out.println("min(" + i + "," + x + ") is " + Math.min(i,x));
System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j));

// There's a corresponding max() method
// that returns the larger of two numbers
System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j));
System.out.println("max(" + x + "," + y + ") is " + Math.max(x,y));
System.out.println("max(" + i + "," + x + ") is " + Math.max(i,x));
System.out.println("max(" + y + "," + j + ") is " + Math.max(y,j));

// The Math library defines a couple
// of useful constants:
System.out.println("Pi is " + Math.PI);
System.out.println("e is " + Math.E);
// Trigonometric methods
// All arguments are given in radians

// Convert a 45 degree angle to radians
double angle = 45.0 * 2.0 * Math.PI/360.0;
System.out.println("cos(" + angle + ") is " + Math.cos(angle));
System.out.println("sin(" + angle + ") is " + Math.sin(angle));

// Inverse Trigonometric methods
// All values are returned as radians

double value = 0.707;

System.out.println("acos(" + value + ") is " + Math.acos(value));
System.out.println("asin(" + value + ") is " + Math.asin(value));
System.out.println("atan(" + value + ") is " + Math.atan(value));

// pow(x, y) returns the x raised
// to the yth power.
System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0,2.0));
System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5));
System.out.println("pow(8, -1) is " + Math.pow(8,-1));

// sqrt(x) returns the square root of x.
for (i=0; i < 10; i++) {
System.out.println(
"The square root of " + i + " is " + Math.sqrt(i));
}

// Finally there's one Random method
// that returns a pseudo-random number
// between 0.0 and 1.0;
System.out.println("Here's one random number: " +
Math.random());
System.out.println("Here's another random number: " +
Math.random());
}
}

-----------------------------------------------------------------------------------
System.in
import java.io.*;
public class ReadString {

public static void main (String[] args) {

// prompt the user to enter their name
System.out.print("Enter your name: ");

// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String userName = null;

// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}

System.out.println("Thanks for the name, " + userName);

}

} //

Locale, Date & Calendar Class
The java.util.Locale.setDefault(Locale newLocale) method sets the default locale for this instance of the Java Virtual Machine.
package com.tutorialspoint;

import java.util.*;

public class LocaleDemo {

public static void main(String[] args) {

// create a new locale
Locale locale1 = new Locale("en", "US", "WIN");

// print locale
System.out.println("Locale:" + locale1);

// set another default locale
Locale.setDefault(new Locale("fr", "FRANCE", "MAC"));

// create a new locale based on new default settings
Locale locale2 = Locale.getDefault();

// print the new locale
System.out.println("Locale::" + locale2);
}
}


DateFormat Class
Date Formatting using SimpleDateFormat:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. For example:

import java.util.*;
import java.text.*;

public class DateDemo {
public static void main(String args[]) {

Date dNow = new Date( );
//SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

System.out.println("Current Date: " + ft.format(dNow));
}
}
NumberFormat Class
NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers.
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class FormatNumberWithCustomNumberFormat {
public static void main(String[] args) {
NumberFormat formatter;
String number;
// 0 --> a digit or 0 if no digit present
formatter = new DecimalFormat("00000");
number = formatter.format(-1234.567);
System.out.println("Number 1: " + number);
formatter = new DecimalFormat("0000.000");
number = formatter.format(-1234.567);
System.out.println("Number 2: " + number);
// # --> a digit or nothing if no digit present
formatter = new DecimalFormat("##");
number = formatter.format(-1234.567);
System.out.println("Number 3: " + number); }

String Class
-----------------------------------------------------------------------------------
In Java programming language String class is sequence of characters. String is not primitive type in java. String class is Object like others Classes i.e (StringBuffer or Math) But Strings are immutable Objects. Immutable means final that can not be changed once declared.

import java.io.*;

public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorialspoint.com");

System.out.print("Return Value :" );
System.out.println(Str.substring(10) );

System.out.print("Return Value :" );
System.out.println(Str.substring(10, 15) );
}
}

StringBuffer Class
The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.
public class Test{
public static void main(String args[]){
StringBuffer sBuffer = new StringBuffer(" test");
sBuffer.append(" String Buffer");
System.ou.println(sBuffer); }

StringBuilder Class
StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters.
import java.lang.*;
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("India ");
System.out.println("string = " + str);
// append character to the StringBuilder
str.append('!');
// convert to string object and print it
System.out.println("After append = " + str.toString());
str = new StringBuilder("Hi ");
System.out.println("string = " + str);
// append integer to the StringBuilder
str.append(123);
// convert to string object and print it
System.out.println("After append = " + str.toString());
}
}


String Tokenizers
In Java, you can StringTokennizer class to split a String into different tokenas by defined delimiter.(space is the default delimiter).
import java.util.StringTokenizer;
public class App {
public static void main(String[] args) {
String str = "This is String , split by StringTokenizer, created by mkyong";
StringTokenizer st = new StringTokenizer(str);

System.out.println("---- Split by space ------");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");

while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
}

Regular Expressions
Regular expressions are a language of string patterns built in to most modern programming languages, including Java 1.4 onward; they can be used for: searching, extracting, and modifying text. This chapter will cover basic syntax and use.
. Dot, any character (may or may not match line terminators, read on)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
However; notice that in Java, you will need to "double escape" these backslashes.
String pattern = "\\d \\D \\W \\w \\S \\s";

* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
\ Escape the next meta-character (it becomes a normal/literal character)
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
" Alternation ('or' statement)
() Grouping
[] Custom character class


import java.util.ArrayList;
import java.util.List;
public class ValidateDemo {
public static void main(String[] args) {
List input = new ArrayList();
input.add("123-45-6789");
input.add("9876-5-4321");
input.add("987-65-4321 (attack)");
input.add("987-65-4321 ");
input.add("192-83-7465");
for (String ssn : input) {
if (ssn.matches("^(\\d{3}-?\\d{2}-?\\d{4})$")) {
System.out.println("Found good SSN: " + ssn);
}
}
}
}


Lihat lebih banyak...

Comentários

Copyright © 2017 DADOSPDF Inc.