TOPIC | TEXT | SYNTAX | Example |
---|---|---|---|
ASCII | Returns the ASCII value of the first character in the string. | ASCII(string) | |
BIT_LENGTH | Returns the number of bits in a string. | BIT_LENGTH(string) | |
LENGTH | Returns the number of characters in a string. | { LENGTH | CHAR_LENGTH | CHARACTER_LENGTH } ( string ) | |
OCTET_LENGTH | Returns the number of bytes in a string. | OCTET_LENGTH(string) | |
CHAR | Returns the character that represents the ASCII value. | { CHAR | CHR } ( int ) | |
CONCAT | Combines strings. | CONCAT(string, string [,...]) | |
DIFFERENCE | Returns the difference between the sounds of two strings. | DIFFERENCE(string, string) | |
HEXTORAW | Converts a hex representation of a string to a string. | HEXTORAW(string) | |
RAWTOHEX | Converts a string to the hex representation. | RAWTOHEX(string) | |
INSTR | Returns the location of a search string in a string. | INSTR(string, searchString, [, startInt]) | |
INSERT Function | Inserts a additional string into the original string at a specified start position. | INSERT(originalString, startInt, lengthInt, addString) | |
LOWER | Converts a string to lowercase. | { LOWER | LCASE } ( string ) | |
UPPER | Converts a string to uppercase. | { UPPER | UCASE } ( string ) | |
LEFT | Returns the leftmost number of characters. | LEFT(string, int) | |
RIGHT | Returns the rightmost number of characters. | RIGHT(string, int) | |
LOCATE | Returns the location of a search string in a string. | LOCATE(searchString, string [, startInt]) | |
POSITION | Returns the location of a search string in a string. | POSITION(searchString, string) | |
LPAD | Left pad the string to the specified length. | LPAD(string, int[, paddingString]) | |
RPAD | Right pad the string to the specified length. | RPAD(string, int[, paddingString]) | |
LTRIM | Removes all leading spaces from a string. | LTRIM(string) | |
RTRIM | Removes all trailing spaces from a string. | RTRIM(string) | |
TRIM | Removes all leading spaces, trailing spaces, or spaces at both ends, from a string. | TRIM ( [ { LEADING | TRAILING | BOTH } [ string ] FROM ] string ) | |
REGEXP_REPLACE | Replaces each substring that matches a regular expression. | REGEXP_REPLACE(inputString, regexString, replacementString) | |
REPEAT | Returns a string repeated some number of times. | REPEAT(string, int) | |
REPLACE | Replaces all occurrences of a search string in a text with another string. | REPLACE(string, searchString [, replacementString]) | |
SOUNDEX | Returns a four character code representing the sound of a string. | SOUNDEX(string) | |
SPACE | Returns a string consisting of a number of spaces. | SPACE(int) | |
STRINGDECODE | Converts a encoded string using the Java string literal encoding format. | STRINGDECODE(string) | |
STRINGENCODE | Encodes special characters in a string using the Java string literal encoding format. | STRINGENCODE(string) | |
STRINGTOUTF8 | Encodes a string to a byte array using the UTF8 encoding format. | STRINGTOUTF8(string) | |
SUBSTRING | Returns a substring of a string starting at a position. | { SUBSTRING | SUBSTR } ( string, startInt [, lengthInt ] ) | |
UTF8TOSTRING | Decodes a byte array in the UTF8 format to a string. | UTF8TOSTRING(bytes) | |
XMLATTR | Creates an XML attribute element of the form "name=value". | XMLATTR(nameString, valueString) | |
XMLNODE | Create an XML node element. | XMLNODE(elementString [, attributesString [, contentString]]) | |
XMLCOMMENT | Creates an XML comment. | XMLCOMMENT(commentString) | |
XMLCDATA | Creates an XML CDATA element. | XMLCDATA(valueString) | |
XMLSTARTDOC | The string " | XMLSTARTDOC() | |
XMLTEXT | Creates an XML text element. | XMLTEXT(valueString) |
SQL basics- complete reference guide - part6 - String functions
Part6: SQL String Functions Complete Reference
java pad string left right - String.format() method
String.format() can be used to left/right pad a given string.
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s); }
public static String padLeft(String s, int n) {
return String.format("%1$#" + n + "s", s); }
...
public static void main(String args[]) throws Exception {
System.out.println(padRight("Howto", 20) + "*");
System.out.println(padLeft("Howto", 25) + "*");
}
Top Java Interview Question : reverse a string using recursion
Best Answer using Recursion :
Less Best Answer :
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
Less Best Answer :
public class JdkReverser implements Reverser {
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return new StringBuffer(str).reverse().toString();
}
}
SQL basics- complete reference guide - part5 - Mathematical Functions
Part5: Mathematical Functions in SQL- Complete Reference
Function | Description | SYNTAX | Example |
---|---|---|---|
ABS | ABS ( { int | long | decimal | double } ) | ||
ACOS | ACOS(double) | ||
ASIN | ASIN(double) | ||
ATAN | ATAN(double) | ||
COS | COS(double) | ||
COT | COT(double) | ||
SIN | SIN(double) | ||
TAN | TAN(double) | ||
ATAN2 | ATAN2(double, double) | ||
BITAND | The bitwise AND operation. | BITAND(long, long) | |
BITOR | The bitwise OR operation. | BITOR(long, long) | |
BITXOR | The bitwise XOR operation. | BITXOR(long, long) | |
MOD | The modulo operation. | MOD(long, long) | |
CEILING | CEILING(double) | ||
DEGREES | DEGREES(double) | ||
EXP | EXP(double) | ||
FLOOR | FLOOR(double) | ||
LOG | LOG(double) | ||
LOG10 | LOG10(double) | ||
RADIANS | RADIANS(double) | ||
SQRT | SQRT(double) | ||
PI | PI() | ||
POWER | POWER(double, double) | ||
RAND | Calling the function without parameter returns the next a pseudo random number. | RAND( [ int ] ) | |
RANDOM_UUID | Returns a new UUID with 122 pseudo random bits. | RANDOM_UUID() | |
ROUND | Rounds to a number of digits. | ROUND(double, digitsInt) | |
ROUNDMAGIC | This function rounds numbers in a good way, but it is slow. | ROUNDMAGIC(double) | |
SECURE_RAND | Generates a number of cryptographically secure random numbers. | SECURE_RAND(int) | |
SIGN | Returns -1 if the value is smaller 0, 0 if zero, and otherwise 1. | SIGN ( { int | long | decimal | double } ) | |
ENCRYPT | Encrypts data using a key. | ENCRYPT(algorithmString, keyBytes, dataBytes) | |
DECRYPT | Decrypts data using a key. | DECRYPT(algorithmString, keyBytes, dataBytes) | |
HASH | Calculate the hash value using an algorithm, and repeat this process for a number of iterations. | HASH(algorithmString, dataBytes, iterationInt) | |
TRUNCATE | Truncates to a number of digits (to the next value closer to 0). | TRUNCATE(double, digitsInt) | |
COMPRESS | Compresses the data using the specified compression algorithm. | COMPRESS(dataBytes [, algorithmString]) | |
EXPAND | Expands data that was compressed using the COMPRESS function. | EXPAND(bytes) | |
ZERO | Returns the value 0. | ZERO() |
SQL basics- complete reference guide - part4 - Aggregate Functions in SQL
Part4: Aggregate Functions in SQL- complete reference sheet
Command/Function | Description | SYNTAX | Example |
---|---|---|---|
AVG | The average (mean) value. | AVG ( [ DISTINCT ] { int | long | decimal | double } ) | |
BOOL_AND | Returns true if all expressions are true. | BOOL_AND(boolean) | |
BOOL_OR | Returns true if any expression is true. | BOOL_OR(boolean) | |
COUNT | The count of all row, or of the non-null values. | COUNT( { * | { [ DISTINCT ] expression } } ) | |
GROUP_CONCAT | Concatenates strings with a separator. | GROUP_CONCAT ( [ DISTINCT ] string [ ORDER BY { expression [ ASC | DESC ] } [,...] ] [ SEPARATOR expression ] ) | |
MAX | The highest value. | MAX(value) | |
MIN | The lowest value. | MIN(value) | |
SUM | The sum of all values. | SUM( [ DISTINCT ] { int | long | decimal | double } ) | |
SELECTIVITY | Estimates the selectivity (0-100) of a value. | SELECTIVITY(value) | |
STDDEV_POP | The population standard deviation. | STDDEV_POP( [ DISTINCT ] double ) | |
STDDEV_SAMP | The sample standard deviation. | STDDEV_SAMP( [ DISTINCT ] double ) | |
VAR_POP | The population variance (square of the population standard deviation). | VAR_POP( [ DISTINCT ] double ) | |
VAR_SAMP | The sample variance (square of the sample standard deviation). | VAR_SAMP( [ DISTINCT ] double ) |
Call one constructor from another in Java
Is this possible to call one constructor from another in Java ?
Yes, it is possible:
Yes, it is possible:
public class Foo
{
private int x;
public Foo()
{
this(1);//calling constructor -->> public Foo(int x)
}
public Foo(int x)
{
this.x = x;
}
}
SQL basics- complete reference guide - part3 - Data Types in SQL
Part3: SQL Data Types Reference
TOPIC | TEXT | SYNTAX | Example |
---|---|---|---|
INT Type | Possible values: -2147483648 to 2147483647. | INT | INTEGER | MEDIUMINT | INT4 | SIGNED | |
BOOLEAN Type | Possible values: TRUE and FALSE. | BOOLEAN | BIT | BOOL | |
TINYINT Type | Possible values are: -128 to 127. | TINYINT | |
SMALLINT Type | Possible values: -32768 to 32767. | SMALLINT | INT2 | YEAR | |
BIGINT Type | Possible values: -9223372036854775808 to 9223372036854775807. | BIGINT | INT8 | |
IDENTITY Type | Auto-Increment value. | IDENTITY | |
DECIMAL Type | Data type with fixed precision and scale. | { DECIMAL | NUMBER | DEC | NUMERIC } ( precisionInt [ , scaleInt ] ) | |
DOUBLE Type | Floating point number. | { DOUBLE [ PRECISION ] | FLOAT | FLOAT4 | FLOAT8 } | |
REAL Type | Single precision floating point number. | REAL | |
TIME Type | The format is hh:mm:ss. | TIME | |
DATE Type | The format is yyyy-MM-dd. | DATE | |
TIMESTAMP Type | The format is yyyy-MM-dd hh:mm:ss[. | { TIMESTAMP | DATETIME | SMALLDATETIME } | |
BINARY Type | Represents a byte array. | { BINARY | VARBINARY | LONGVARBINARY | RAW | BYTEA } [ ( precisionInt ) ] | |
OTHER Type | This type allows storing serialized Java objects. | OTHER | |
VARCHAR Type | Unicode String. | { VARCHAR | LONGVARCHAR | VARCHAR2 | NVARCHAR | NVARCHAR2 | VARCHAR_CASESENSITIVE} [ ( precisionInt ) ] | |
VARCHAR_IGNORECASE Type | Same as VARCHAR, but not case sensitive when comparing. | VARCHAR_IGNORECASE [ ( precisionInt ) ] | |
CHAR Type | This type is supported for compatibility with other databases and older applications. | { CHAR | CHARACTER | NCHAR } [ ( precisionInt ) ] | |
BLOB Type | Like BINARY, but intended for very large values such as files or images. | { BLOB | TINYBLOB | MEDIUMBLOB | LONGBLOB | IMAGE | OID } [ ( precisionInt ) ] | |
CLOB Type | CLOB is like VARCHAR, but intended for very large values. | { CLOB | TINYTEXT | TEXT | MEDIUMTEXT | LONGTEXT | NTEXT | NCLOB } [ ( precisionInt ) ] | |
UUID Type | Universally unique identifier. | UUID | |
ARRAY Type | An array of values. | ARRAY |
SQL basics- complete reference guide - part2 - DDL
Part2: DDL -Data Definition Language Reference
Command | Description | SYNTAX | Example |
---|---|---|---|
ALTER INDEX RENAME | Renames an index. | ALTER INDEX indexName RENAME TO newIndexName | |
ALTER SCHEMA RENAME | Renames a schema. | ALTER SCHEMA schema RENAME TO newSchemaName | |
ALTER SEQUENCE | Changes the next value and the increment of a sequence. | ALTER SEQUENCE sequenceName [ RESTART WITH long ] [ INCREMENT BY long ] | |
ALTER TABLE ADD | Adds a new column to a table. | ALTER TABLE tableName ADD name dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ AUTO_INCREMENT | IDENTITY ] [ BEFORE columnName ] | |
ALTER TABLE ADD CONSTRAINT | Adds a constraint to a table. | ALTER TABLE tableName ADD constraint [ CHECK | NOCHECK ] | |
ALTER TABLE ALTER | Changes the data type of a column, rename a column, change the identity value, or change the selectivity. | ALTER TABLE tableName ALTER COLUMN columnName { { dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ AUTO_INCREMENT | IDENTITY ] } | { RENAME TO name } | { RESTART WITH long } | { SELECTIVITY int } | { SET DEFAULT expression } | { SET NULL } | { SET NOT NULL } } | |
ALTER TABLE DROP COLUMN | Removes a column from a table. | ALTER TABLE tableName DROP COLUMN columnName | |
ALTER TABLE DROP CONSTRAINT | Removes a constraint or a primary key from a table. | ALTER TABLE tableName DROP { CONSTRAINT [ IF EXISTS ] constraintName | PRIMARY KEY } | |
ALTER TABLE SET | Disables or enables referential integrity checking for a table. | ALTER TABLE tableName SET REFERENTIAL_INTEGRITY { FALSE | TRUE [ CHECK | NOCHECK ] } | |
ALTER TABLE RENAME | Renames a table. | ALTER TABLE tableName RENAME TO newName | |
ALTER USER ADMIN | Switches the admin flag of a user on or off. | ALTER USER userName ADMIN { TRUE | FALSE } | |
ALTER USER RENAME | Renames a user. | ALTER USER userName RENAME TO newUserName | |
ALTER USER SET PASSWORD | Changes the password of a user. | ALTER USER userName SET { PASSWORD string | SALT bytes HASH bytes } | |
ALTER VIEW | Recompiles a view after the underlying tables have been changed or created. | ALTER VIEW viewName RECOMPILE | |
ANALYZE | Updates the selectivity statistics of all tables. | ANALYZE [ SAMPLE_SIZE rowCountInt ] | |
COMMENT | Sets the comment of a database object. | COMMENT ON { { COLUMN [ schemaName. ] tableName.columnName } | { { TABLE | VIEW | CONSTANT | CONSTRAINT | ALIAS | INDEX | ROLE | SCHEMA | SEQUENCE | TRIGGER | USER | DOMAIN } [ schemaName. ] objectName } } IS expression | |
CREATE AGGREGATE | Creates a new user-defined aggregate function. | CREATE AGGREGATE [ IF NOT EXISTS ] newAggregateName FOR className | |
CREATE ALIAS | Creates a new function alias. | CREATE ALIAS [ IF NOT EXISTS ] newFunctionAliasName [ DETERMINISTIC ] { FOR classAndMethodName | AS sourceCodeString } | |
CREATE CONSTANT | Creates a new constant. | CREATE CONSTANT [ IF NOT EXISTS ] newConstantName VALUE expression | |
CREATE DOMAIN | Creates a new data type (domain). | CREATE DOMAIN [ IF NOT EXISTS ] newDomainName AS dataType [ DEFAULT expression ] [ [ NOT ] NULL ] [ SELECTIVITY selectivity ] [ CHECK condition ] | |
CREATE INDEX | Creates a new index. | CREATE { [ UNIQUE ] [ HASH ] INDEX [ IF NOT EXISTS ] newIndexName | PRIMARY KEY [ HASH ] } ON tableName ( indexColumn [,...] ) | |
CREATE LINKED TABLE | Creates a table link to an external table. | CREATE [ [ GLOBAL | LOCAL ] TEMPORARY ] LINKED TABLE [ IF NOT EXISTS ] name ( driverString, urlString, userString, passwordString, [ originalSchemaString, ] originalTableString ) [ EMIT UPDATES | READONLY ] | |
CREATE ROLE | Creates a new role. | CREATE ROLE [ IF NOT EXISTS ] newRoleName | |
CREATE SCHEMA | Creates a new schema. | CREATE SCHEMA [ IF NOT EXISTS ] name [ AUTHORIZATION ownerUserName ] | |
CREATE SEQUENCE | Creates a new sequence. | CREATE SEQUENCE [ IF NOT EXISTS ] newSequenceName [ START WITH long ] [ INCREMENT BY long ] [ CACHE long ] | |
CREATE TABLE | Creates a new table. | CREATE [ CACHED | MEMORY ] [ TEMP | [ GLOBAL | LOCAL ] TEMPORARY ] TABLE [ IF NOT EXISTS ] name { { ( { columnDefinition | constraint } [,...] ) [ AS select ] } | { AS select } } [ ENGINE tableEngineName ] [ TRANSACTIONAL ] [ NOT PERSISTENT ] | |
CREATE TRIGGER | Creates a new trigger. | CREATE TRIGGER [ IF NOT EXISTS ] newTriggerName { BEFORE | AFTER | INSTEAD OF } { INSERT | UPDATE | DELETE | SELECT | ROLLBACK } [,...] ON tableName [ FOR EACH ROW ] [ QUEUE int ] [ NOWAIT ] CALL triggeredClassName | |
CREATE USER | Creates a new user. | CREATE USER [ IF NOT EXISTS ] newUserName { PASSWORD string | SALT bytes HASH bytes } [ ADMIN ] | |
CREATE VIEW | Creates a new view. | CREATE [ OR REPLACE ] [ FORCE ] VIEW [ IF NOT EXISTS ] newViewName [ ( columnName [,...] ) ] AS select | |
DROP AGGREGATE | Drops an existing user-defined aggregate function. | DROP AGGREGATE [ IF EXISTS ] aggregateName | |
DROP ALIAS | Drops an existing function alias. | DROP ALIAS [ IF EXISTS ] existingFunctionAliasName | |
DROP ALL OBJECTS | Drops all existing views, tables, sequences, schemas, function aliases, roles, user-defined aggregate functions, domains, and users (except the current user). | DROP ALL OBJECTS [ DELETE FILES ] | |
DROP CONSTANT | Drops a constant. | DROP CONSTANT [ IF EXISTS ] constantName | |
DROP DOMAIN | Drops a data type (domain). | DROP DOMAIN [ IF EXISTS ] domainName | |
DROP INDEX | Drops an index. | DROP INDEX [ IF EXISTS ] indexName | |
DROP ROLE | Drops a role. | DROP ROLE [ IF EXISTS ] roleName | |
DROP SCHEMA | Drops a schema. | DROP SCHEMA [ IF EXISTS ] schemaName | |
DROP SEQUENCE | Drops a sequence. | DROP SEQUENCE [ IF EXISTS ] sequenceName | |
DROP TABLE | Drops an existing table, or a list of tables. | DROP TABLE [ IF EXISTS ] tableName [,...] [ CASCADE | RESTRICT ] | |
DROP TRIGGER | Drops an existing trigger. | DROP TRIGGER [ IF EXISTS ] triggerName | |
DROP USER | Drops a user. | DROP USER [ IF EXISTS ] userName | |
DROP VIEW | Drops an existing view. | DROP VIEW [ IF EXISTS ] viewName [ RESTRICT | CASCADE ] | |
TRUNCATE TABLE | Removes all rows from a table. | TRUNCATE TABLE tableName |
SQL basics- complete reference guide - part1 - DML
Part1: DML-Data Manipulation Language
Command | Description | SYNTAX | Example |
---|---|---|---|
SELECT | Selects data from a table or multiple tables. | SELECT [ TOP term ] [ DISTINCT | ALL ] selectExpression [,...] FROM tableExpression [,...] [ WHERE expression ] [ GROUP BY expression [,...] ] [ HAVING expression ] [ { UNION [ ALL ] | MINUS | EXCEPT | INTERSECT } select ] [ ORDER BY order [,...] ] [ LIMIT expression [ OFFSET expression ] [ SAMPLE_SIZE rowCountInt ] ] [ FOR UPDATE ] | |
INSERT | Inserts a new row / new rows into a table. | INSERT INTO tableName [ ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) } [,...] | [ DIRECT ] [ SORTED ] select } | |
UPDATE | Updates data in a table. | UPDATE tableName [ [ AS ] newTableAlias ] SET { columnName= { DEFAULT | expression } } [,...] [ WHERE expression ] | |
DELETE | Deletes rows form a table. | DELETE FROM tableName [ WHERE expression ] | |
BACKUP | Backs up the database files to a . | BACKUP TO fileNameString | |
CALL | Calculates a simple expression. | CALL expression | |
EXPLAIN | Shows the execution plan for a statement. | EXPLAIN { [ PLAN FOR ] | ANALYZE } { select | insert | update | delete | merge } | |
MERGE | Updates existing rows, and insert rows that don't exist. | MERGE INTO tableName [ ( columnName [,...] ) ] [ KEY ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) } [,...] | select } | |
RUNSCRIPT | Runs a SQL script from a file. | RUNSCRIPT FROM fileNameString [ scriptCompression ] [ CIPHER cipher PASSWORD string ] [ CHARSET charsetString ] | |
SCRIPT | Creates a SQL script from the database. | SCRIPT [ SIMPLE ] [ NODATA ] [ NOPASSWORDS ] [ NOSETTINGS ] [ DROP ] [ BLOCKSIZE blockSizeInt ] [ TO fileNameString [ scriptCompression ] [ CIPHER cipher PASSWORD string ] ] [ CHARSET charsetString ] | |
SHOW | Lists the schemas, tables, or the columns of a table. | SHOW { SCHEMAS | TABLES [ FROM schemaName ] | COLUMNS FROM tableName [ FROM schemaName ] } |
Scenarios in which Serialization cannot happen
What are the special cases in which serialization cannot happen?
-> There are following scenarios in which serialization cannot happen:
a. Variables are transient.
b. Variables are static.
c. Base class variables are serialized if class itself is serializable.
-> There are following scenarios in which serialization cannot happen:
a. Variables are transient.
b. Variables are static.
c. Base class variables are serialized if class itself is serializable.
java prevent sql injection - using PreparedStatement
PreparedStatement is the best way to prevent sql injection in java, rather than escaping strings.
Here's a simple example taking the user's input as the parameters:
public insertUser(String name, String email) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = setupTheDatabaseConnectionSomehow();
stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
finally {
try {
if (stmt != null) { stmt.close(); }
}
catch (Exception e) {
// log this error
}
try {
if (conn != null) { conn.close(); }
}
catch (Exception e) {
// log this error
}
}
}
No matter what characters are in name and email, those characters will be placed directly in the database. They won't affect the INSERT statement in any way.
There are different set methods for different data types -- which one you use depends on what your database fields are. For example, if you have an INTEGER column in the database, you should use a
setInt
method. The PreparedStatement documentation lists all the different methods available for setting and getting data.redirect message to IO stream
How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);
java socket connect read string
Java - create socket connection to HOST:PORT and read message from there
import java.io.*;
import java.net.*;
import java.util.*;
public class Time_Server_Socket_Test_Java {
public static void main(String[] args) {
try {
Socket s = new Socket(HOST, PORT);//use your own HOST:PORT
try {
InputStream inStream = s.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(line);
}
} finally {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
How to serialize variables selectively
In a Java class, one has 10 variables. One wants to serialize only 3 variables,how can this be achieved?
->Make variables as 'transient' which are not to be serialized.
->Make variables as 'transient' which are not to be serialized.
maximize a JFrame window in java
How to Maximize a JFrame :
JFrame myFrame = new JFrame();
myFrame.setVisible(true);
myFrame.setExtendedState(myFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
The usage of Java packages.
Explain the usage of Java packages.
A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names.
Packages access level also allows you to protect data from being used by the non-authorized classes.
Java: difference between private, protected, and public?
These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults
java show window JFrame JDialog always on top
We have to use this feature of java.awt.Window : Window.alwaysOnTop(boolean);
Example code :
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Always_on_Top_JFrame_JAVA{
public static void main(String[] args) {
JFrame frame = new JFrame("Title - always on top :D ");
// Set's the window to be "always on top"
frame.setAlwaysOnTop( true );
frame.setLocationByPlatform( true );
frame.add( new JLabel(" Always on TOP ") );
frame.pack();
frame.setVisible( true );
}
}
Order of catching exception in java
Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNotFoundException is inherited from the IOException.
A. Yes, it does. The FileNotFoundException is inherited from the IOException.
Exception's subclasses have to be caught first.
Exception
^
|
IOException
^
|
FileNotFoundException
So while catching exceptions, we must catch the low level exception first - here : FileNotFoundException .
#The hierarchy in Java Exception framework :
wrapper classes in Java
Describe the wrapper classes in Java.Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Following table lists the primitive types and the corresponding wrapper classes:
Primitive - Wrapper
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
Java Class as Applet as well as Application
Can you write a Java class that could be used both as an applet as well as an application?
A. Yes. Add a main() method to the applet.
A. Yes. Add a main() method to the applet.
Bring JFrame JDialog Window to front java swing
To bring JFrame or JDialog ... or Window (JFrame and JDialog inherits Window) to front in JAVA, fun the code below :
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
//myFrame is object of Window or JFrame
public void run() {
myFrame.toFront();
myFrame.repaint();
}
});
Redirect Standard System Output and Error Message to PrintStream in Java
In a Java program, how can you divert standard system output or error messages, say to a file?
->We can achieve this by using
public static void setErr(PrintStream err)
and public static void setOut(PrintStream out) methods.
By default, they both point at the system console. The following example redirects Out and Err messages to 'error.txt' file
Stream stream = new Stream(new FileOutputStream("error.txt"));
System.setErr(stream);
System.setOut(stream);
You can redirect the Err and Out stream to any PrintStream object.
->We can achieve this by using
public static void setErr(PrintStream err)
and public static void setOut(PrintStream out) methods.
By default, they both point at the system console. The following example redirects Out and Err messages to 'error.txt' file
Stream stream = new Stream(new FileOutputStream("error.txt"));
System.setErr(stream);
System.setOut(stream);
You can redirect the Err and Out stream to any PrintStream object.
concatenate arrays of any type - java
Combining two arrays of any type
public static T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
For combining arbitrary number of arrays
difference between an interface and an abstract class
What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)
Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.
Differences are as follows:
* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:
* Neither Abstract classes or Interface can be instantiated.
How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}
How to define an Interface?Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}
Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.
Differences are as follows:
* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:
* Neither Abstract classes or Interface can be instantiated.
How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}
How to define an Interface?Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}
Adding image to JPanel Java
Adding Image to JPanel
BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add( picLabel );
:D
Read time from internet time server - working java code
Read time from internet time server - working java code
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This program makes a socket connection to the atomic clock in Boulder,
* Colorado, and prints the time that the server sends.
*/
public class Time_Server_Socket_Test_Java {
public static void main(String[] args) {
try {
Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13);
try {
InputStream inStream = s.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(line);
}
} finally {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
iterate through map hashmap linkedhashmap in java
How to iterate through Map.. MashMap, LinkedHashMap ... in Java
Method 1 : If you're only interested in the keys, you can iterate through the keySet() of the map:
Method 1 : If you're only interested in the keys, you can iterate through the keySet() of the map:
Mapmap = ...;
for (String key : map.keySet()) {
// ...
}
Method 2 :java escape text in regular expression
Java's a built-in way to escape arbitrary text so that it can be included in a regular expression-
For example, users enter "$5", we can match that exactly rather than a "5" after the end of input.
Just do this : to escape text in regex
For example, users enter "$5", we can match that exactly rather than a "5" after the end of input.
Just do this : to escape text in regex
Pattern.quote("$5");
use of @override annotation in java - why ?
The @override annotation is most useful as a compile-time reminder that the intention of the method is to override a parent method. See this example:
import java.util.HashSet;
import java.util.Set;
/**
* Override_Annotation_Usage_Example, from Effective Java
*/
java reflection - what is - 101 tutorial
The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
A simple code example of this in Java (imagine the object in question is foo) :
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.
There are some good reflection examples to get started : at http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html
Bubble sort working source code - C/C++
Bubble sort working source code - C/C++
#include <stdio.h>
#include <iostream.h>
void bubbleSort(int *array,int length)//Bubble sort function
{
int i,j;
for(i=0;i<length;i++)
{
for(j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp=array[i]; //swap
array[i]=array[j];
array[j]=temp;
}
}
}
}
void printElements(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<length;i++)
cout<<array[i]<<endl;
}
void main()
{
int a[]={9,6,5,23,2,6,2,7,1,8}; // array to sort
bubbleSort(a,10); //call to bubble sort
printElements(a,10); // print elements
}
Subscribe to:
Posts
(
Atom
)