About us

Join us FREE!

Write and publish your ideas, thoughts, blogs or articles on any topic. You are at right place for guest blogging. Post tutorials for knowledge sharing. Upload respective images and tag your YouTube or Facebook videos with the articles and share it on various social media with simple steps. Join us Free to add your post.



Monthly trending articles on ConnectClue

Anuska  posted in Poetry

Showing results for Er Satya Remove
Differences between String[] and ArrayList

String[] is an array of Strings while ArrayList is a generic class that takes different types of objects. Therefore we can only perform normal array operations with String[]. However, we can use additional, convenient utilities such as isEmpty(), iterator, etc with ArrayList since it also implements Collection Interface.

ArrayList has some neat methods, such as add(), remove(), and contains().

An array String[] cannot expand its size. You can initialize it once giving it a permanent size:

String[] myStringArray = new String[10]();
myStringArray[0] = "Test";
An ArrayList is variable in size. You can add and remove items dynamically:
ArrayList myStringArrayList = new ArrayList();
myStringArrayList.add("Test");
myStringArrayList.remove(1);
Furthermore, we can sort, clear, addall, and a lot more functions and can use while using an ArrayList. 

Post updated on:  Feb 20, 2023 1:18:22 AM

Group a list of objects by an attribute

This will add the employee object to the HashMap with locationID as key.
HashMap> hashMap = new HashMap>>();
Iterate over this code and add an employee to the HashMap:
if (!hashMap.containsKey(locationId)) {
    List list = new ArrayList >();
list.add(employee ); hashMap.put(locationId, list); } else { hashMap.get(locationId).add(employee ); }
If you want all the employee with particular location details then you can use this:
hashMap.get(locationId);
which will get you all the employee with the same the location ID.

Java 8 groupingBy Collector

You can just use the Collectors.groupingBy() bypassing the grouping logic as a function parameter and you will get the split list with the key parameter mapping. Note that using Optional is used to avoid unwanted NPE when the provided list is null

public static  Map> groupBy(List list, Function keyFunction) {
    return Optional.ofNullable(list)
            .orElseGet(ArrayList::new)
            .stream()
            .collect(Collectors.groupingBy(keyFunction));
}
Now you can groupBy anything with this. For the use case here in the question
MapEmployee>> map = groupBy(employee list, Employee::getLocation);

Post updated on:  Feb 20, 2023 1:17:35 AM

How to add double quotes automatically, converting a list of strings as comma-separated values?


We can perform it in two steps with StringUtils only,
List s = new ArrayList<>();
s.add("ten");
s.add("twenty");
s.add("thirty");

String step1 = StringUtils.join(s, "\", \"");// Join with ", "
String step2 = StringUtils.wrap(step1, "\"");// Wrap step1 with "

System.out.println(step2);
Output,
"ten", "twenty", "thirty"

Post updated on:  Feb 20, 2023 1:14:16 AM

When is the @JsonProperty property used and what is it used for?


Here's a good example. I use it to rename the variable because the JSON is coming from a .Net environment where properties start with an upper-case letter.

public class Parameter {
  @JsonProperty("Name")
  public String name;
  @JsonProperty("Value")
  public String value; 
}
This correctly parses to/from the JSON:
"Parameter":{
  "Name":"Parameter-Name",
  "Value":"Parameter-Value"
}

Post updated on:  Feb 20, 2023 1:13:27 AM

What is REST API error handling best practices?


I wouldn't return a 200 unless there really was nothing wrong with the request. From RFC2616, 200 means "the request has succeeded."
If the client's storage quota has been exceeded (for whatever reason), I'd return a 403 (Forbidden):

This tells the client that the request was OK, but that it failed (something a 200 doesn't do). This also gives you the opportunity to explain the problem (and its solution) in the response body.

What other specific error conditions?

The main choice is done you want to treat the HTTP status code as part of your REST API or not.

Both ways work fine. I agree that strictly speaking, one of the ideas of REST is that you should use the HTTP Status code as a part of your API (return 200 or 201 for a successful operation and a 4xx or 5xx depending on various error cases.) However, there is no REST police. You can do what you want. I have seen far more egregious non-REST APIs being called "RESTful."
At this point (August 2015) I do recommend that you use the HTTP Status code as part of your API. It is now much easier to see the return code when using frameworks than it was in the past. In particular, it is now easier to see the non-200 return case and the body of non-200 responses than it was in the past.

The HTTP Status code is part of your API
  1. You will need to carefully pick 4xx codes that fit your error conditions. You can include a rest, XML, or plaintext message as the payload that includes a sub-code and a descriptive comment.
  2. The clients will need to use a software framework that enables them to get to the HTTP-level status code. Usually doable, not always straightforward.
  3. The clients will have to distinguish between HTTP status codes that indicate a communications error and your own status codes that indicate an application-level issue.
  4. The HTTP Status code is NOT part of your API
    1. The HTTP status code will always be 200 if your app received the request and then responded (both success and error cases)
    2. All of your responses should include "envelope" or "header" information. Typically something like:
      envelope_ver: 1.0
      status:  # use any codes you like. Reserve a code for success. 
      msg: "ok" # A human string that reflects the code. Useful for debugging.
      data: ...  # The data of the response, if any.
    3. This method can be easier for clients since the status for the response is always in the same place (no sub-codes needed), no limits on the codes, and no need to fetch the HTTP-level status code.
Main issues:
  1. Be sure to include version numbers so you can later change the semantics of the api if needed.
  2. Document

Do remember that 5xx errors are server-side, aka the client cannot change anything to its request to make the request pass. If the client's quota is exceeded, that's definitely not a server error, so 5xx should be avoided.

This is extremely late to the party, but now, in the year 2013, we have a few media types to cover error handling in a common distributed (RESTful) fashion. See "vnd.error", application/vnd.error+json (https://github.com/blongden/vnd.error) and "Problem Details for HTTP APIs", application/problem+json (https://datatracker.ietf.org/doc/html/draft-nottingham-http-problem-05).

There are two sorts of errors. Application errors and HTTP errors. The HTTP errors are just to let your AJAX handler know that things went fine and should not be used for anything else.

5xx Server Error

500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates (RFC 2295 )
507 Insufficient Storage (WebDAV) (RFC 4918 )
509 Bandwidth Limit Exceeded (Apache bw/limited extension)
510 Not Extended (RFC 2774 )

2xx Success

200 OK
201 Created
202 Accepted
203 Non-Authoritative Information (since HTTP/1.1)
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status (WebDAV)
However, how you design your application errors is really up to you. Stack Overflow for example sends out an object with responsedata and message properties. The response I believe contains true or false to indicate if the operation was successful (usually for write operations). The data contains the payload (usually for read operations) and the message contains any additional metadata or useful messages (such as error messages when the response is false).

Agreed. The basic philosophy of REST is to use the web infrastructure. The HTTP Status codes are the messaging framework that allows parties to communicate with each other without increasing the HTTP payload. They are already established universal codes conveying the status of the response, and therefore, to be truly RESTful, the applications must use this framework to communicate the response status.
Sending an error response in an HTTP 200 envelope is misleading, and forces the client (API consumer) to parse the message, most likely in a non-standard, or proprietary way. This is also not efficient - you will force your clients to parse the HTTP payload every single time to understand the "real" response status. This increases processing, adds latency, and creates an environment for the client to make mistakes.

Don't forget the 5xx errors as well for application errors.
In this case what about 409 (Conflict)? This assumes that the user can fix the problem by deleting stored resources.
Otherwise, 507 (not entirely standard) may also work. I wouldn't use 200 unless you use 200 for errors in general.

If the client quota is exceeded it is a server error, avoid 5xx in this instance.


Post updated on:  Feb 20, 2023 1:12:58 AM

hardcode string vs @string in Java code - Android

Using multiple strings of the same value no matter the method (Strings.xml vs programmatically) doesn't seem to have any associated overhead. According to Oracle "All literal strings and string-valued constant expressions are interned" which means that the object is reused rather than re-created if you use it again.

That way you have a fixed place to alter all your strings within the project. Let us say you used the same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.

Well, strings.xml would have to be parsed, wouldn't it? Then I suppose hardcoded would be best for performance, though probably unnoticeable at runtime. People do choose to use it though in order to have all the strings in one spot in case there are plans to translate the app.

There are many benefits to setting the strings in a strings.xml file; in a nutshell, it allows you to use the same string in multiple locations, which is good if you somehow need to modify the string later. It also allows you to display the same text in different languages; hardcoding the string doesn't give you all those options.
BTW, you don't need to put every text in the strings.XML file; only the ones that might be used in multiple places in the application.
The general rule for placing strings in the strings.xml file are these:
  • Will it be used in multiple locations 
  • Will it be used in multiple languages 
  • Will it be dynamic or static 

Post updated on:  Feb 20, 2023 1:12:38 AM

how to replace "(double quotes) in a string with \" in java 

Example - 

str = str.replace("\"", "\\\"")

Avoid using replaceAll since it uses regex syntax in description of what to replace and how to replace, which means that \ will have to be escaped in string "\\" but also in regex \\ (needs to be written as "\\\\" string) which means that we would need to use.
str = str.replaceAll("\"", "\\\\\"");
str = str.replaceAll("\"", Matcher.quoteReplacement("\\\""))

How do I retrieve query parameters in a Spring Boot controller?

Use @RequestParam

@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String empId){

    Emp i = empDao.findOne(empId);              
String EmpName = i.getEmpName();
String dept= i.getDept(); return i; }



Storing a new object as the value of a hashmap?

HashMap mapper = new HashMap();
mapper.put("Satya", new Emp("Satya"));
... Emp value = mapper.get("Satya"); Integer memory = value.getMemory();

Post updated on:  Feb 20, 2023 1:12:06 AM

How do I add headers for requests from an API?


The sample code:

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
    
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return await response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 08 })
  .then((data) => {
    console.log(data); // JSON data parsed by `response.json()` call
  });


 implementation based on the code above:

fetch(url, {
        headers: {
            "User-Agent": "MyAppName/Version# (Language=Javascript; Platform: Linux)"
        }
    }).then(function(resp) {
        return resp.json();
    }).then(function(data){...

Post updated on:  Feb 20, 2023 1:11:29 AM

Java Variables - A variable is a container that holds the value while the Java program is executed. A variable is assigned with a data type. The variable is the name of a memory location. 

A variable is the name of a reserved area allocated in memory. In other words, it is the name of the memory location. It is a combination of "vary + able" which means 
its value can be changed.


Types of Variables

There are three types of variables in Java:

local variable
instance variable
static variable


1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class 
aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.


2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.


3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all 
the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.


Example 

public class A  
{  
    static int x=10;    //static variable  
    void method()  
    {    
        int y=20;        //local variable    
    }  
    public static void main(String args[])  
    {  
        int data=100;//instance variable    
    }  



Java Variable Example: Add Two Numbers

public class Simple{    
public static void main(String[] args){    
int a=10;    
int b=10;    
int c=a+b;    
System.out.println(c);    
}  
}    



Post updated on:  Feb 20, 2023 1:05:44 AM

Operators in Java - is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Operator Precedence


Operator Type      Category          Precedence   

Unary                        postfix           expr++ expr--
prefix                        ++expr --expr +expr -expr ~ !
Arithmetic                     multiplicative * / %
additive                    + -
Shift                         shift << >> >>>
Relational                 comparison < > <= >= instanceof
equality                         == !=
Bitwise                        bitwise AND &
bitwise                          exclusive OR ^
bitwise                          inclusive OR |
Logical                        logical AND &&
logical                            OR ||
Ternary                         ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=


Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:


incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean


Java Unary Operator Example: ++ and --

public class OperatorExample{  
public static void main(String args[]){  
int x=10;  
System.out.println(x++);//10 (11)  
System.out.println(++x);//12  
System.out.println(x--);//12 (11)  
System.out.println(--x);//10  
}}  


Java Unary Operator Example 2: ++ and --

public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=10;  
System.out.println(a++ + ++a);//10+12=22  
System.out.println(b++ + b++);//10+11=21  
  
}}  


Java Unary Operator Example: ~ and !


public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=-10;  
boolean c=true;  
boolean d=false;  
System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
System.out.println(!c);//false (opposite of boolean value)  
System.out.println(!d);//true  
}}  


Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example

public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
System.out.println(a+b);//15  
System.out.println(a-b);//5  
System.out.println(a*b);//50  
System.out.println(a/b);//2  
System.out.println(a%b);//0  
}}  


Java Arithmetic Operator Example: Expression

public class OperatorExample{  
public static void main(String args[]){  
System.out.println(10*10/5+3-1*4/2);          //21
}}  


Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

Java Left Shift Operator Example

public class OperatorExample{  
public static void main(String args[]){  
System.out.println(10<<2);//10*2^2=10*4=40  
System.out.println(10<<3);//10*2^3=10*8=80  
System.out.println(20<<2);//20*2^2=20*4=80  
System.out.println(15<<4);//15*2^4=15*16=240  
}}  


Java Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand.

Java Right Shift Operator Example

public OperatorExample{  
public static void main(String args[]){  
System.out.println(10>>2);//10/2^2=10/4=2          //2
System.out.println(20>>2);//20/2^2=20/4=5           //5
System.out.println(20>>3);//20/2^3=20/8=2           //2
}}  


Java Shift Operator Example: >> vs >>>

public class OperatorExample{  
public static void main(String args[]){  
    //For positive number, >> and >>> works same  
    System.out.println(20>>2);                                        //5
    System.out.println(20>>>2);                                        //5
    //For negative number, >>> changes parity bit (MSB) to 0  
    System.out.println(-20>>2);                                      //-5
    System.out.println(-20>>>2);                                       // 1073741819
}}  


Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.


public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int c=20;  
System.out.println(a
System.out.println(a
}}  


Java AND Operator Example: Logical && vs Bitwise &

public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int c=20;  
System.out.println(a
System.out.println(a);//10 because second condition is not checked           //10
System.out.println(a
System.out.println(a);//11 because second condition is checked                 //11
}}  


Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false.


The bitwise | operator always checks both conditions whether first condition is true or false.

public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int c=20;  
System.out.println(a>b||a
System.out.println(a>b|a
//|| vs |  
System.out.println(a>b||a++
System.out.println(a);//10 because second condition is not checked            //10
System.out.println(a>b|a++
System.out.println(a);//11 because second condition is checked                //11
}}  


Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statements and is used a lot in Java programming. It is the only conditional operator which takes 
three operands.

Java Ternary Operator Example

public class OperatorExample{  
public static void main(String args[]){  
int a=2;  
int b=5;  
int min=(a
System.out.println(min);     //2
}}  


Java Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left.

Java Assignment Operator Example

public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=20;  
a+=4;//a=a+4 (a=10+4)  
b-=4;//b=b-4 (b=20-4)  
System.out.println(a);     //14
System.out.println(b);       //16
}}  


Java Assignment Operator Example

public class OperatorExample{  
public static void main(String[] args){  
int a=10;  
a+=3;//10+3  
System.out.println(a);     //13
a-=4;//13-4  
System.out.println(a);      //9
a*=2;//9*2  
System.out.println(a);      //18
a/=2;//18/2  
System.out.println(a);      //9
}}  


Java Assignment Operator Example: Adding short

public class OperatorExample{  
public static void main(String args[]){  
short a=10;  
short b=10;  
//a+=b;//a=a+b internally so fine  
a=a+b;//Compile time error because 10+10=20 now int  
System.out.println(a);      // compile time error
}}  


After type cast:

public class OperatorExample{  
public static void main(String args[]){  
short a=10;  
short b=10;  
a=(short)(a+b);//20 which is int now converted to short  
System.out.println(a);      // 20
}}  


Post updated on:  Feb 20, 2023 1:05:12 AM

Java Keywords

Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are predefined words by Java so they cannot be 
used as a variable or object name or class name.


List of Java Keywords

A list of Java keywords or reserved words are given below:

abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It can have abstract and 
non-abstract methods.

boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.

break: Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program at specified conditions.

byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.

case: Java case keyword is used with the switch statements to mark blocks of text.

catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.

char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters.
class: Java class keyword is used to declare a class.
continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

default: Java default keyword is used to specify the default block of code in a switch statement.

do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several times.

double: Java double keyword is used to declare a variable that can hold a 64-bit floating-point number.

else: Java else keyword is used to indicate the alternative branches in an if statement.

enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.

extends: Java extends keyword is used to indicate that a class is derived from another class or interface.

final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a variable. It is used to restrict the user from updating the 
value of the variable.

finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether an exception is handled or not.

float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.

for: Java for a keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some condition becomes true. If the number 
of iteration is fixed, it is recommended to use for loop.

if: Java if keyword tests the condition. It executes the if block if the condition is true.

implements: Java implements keyword is used to implement an interface.

import: Java import keyword makes classes and interfaces available and accessible to the current source code.

instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.

int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.

interface: Java interface keyword is used to declare an interface. It can have only abstract methods.

long: Java long keyword is used to declare a variable that can hold a 64-bit integer.

native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).

new: Java new keyword is used to create new objects.

null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.

package: Java package keyword is used to declare a Java package that includes the classes.

private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.

protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the package but through inheritance only. It can't be 
applied with the class.

public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.

return: Java return keyword is used to return from a method when its execution is complete.

short: Java short keyword is used to declare a variable that can hold a 16-bit integer.

static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is mainly used for memory management.

strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.

super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to invoke the immediate parent class method.

switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against 
multiple values.

synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.

this: Java this keyword can be used to refer to the current object in a method or constructor.

throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exceptions. It is followed by an instance.

throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with throws.

transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.

void: Java void keyword is used to specify that a method does not have a return value.

volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.

while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iterations is not fixed, it is 
recommended using the while loop.

Post updated on:  Feb 20, 2023 1:04:53 AM

Features of Java


These are the most important features of the Java language is given below.

1.  Simple
2.  Object-Oriented
3.  Portable
4.  Platform independent
5.  Secured
6.  Robust
7.  Architecture Neutral
8.  Interpreted
9.  High Performance
10. Multithreaded
11. Distributed
12. Dynamic


Simple

According to Sun Microsystem, Java language is a simple programming language because:

Java is very easy to learn, and its syntax is simple, clean, and easy to understand. 
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.


Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. 

Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules.

The basic concepts of OOPs are:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation


Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.


Platform Independent

Java is platform independent

Java is platform-independent because it is different from other languages like C, C++, etc. which are compiled into platform-specific machines while Java is a 
write-once, run-anywhere language. A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top of other hardware-based platforms. 
It has two components:

Runtime Environment
API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into 
bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).


Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

No explicit pointer

Java Programs run inside a virtual machine sandbox

Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. 
It adds security by separating the package for the classes of the local file system from those that are imported from network sources.

Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.

Security Manager: It determines what resources a class can access such as reading and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.


Robust

Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.
There are exception-handling and the type checking mechanism in Java. All these points make Java robust.


Architecture-neutral

Java is architecture neutral because there are no implementation-dependent features, for example, the size of primitive types is fixed.

In C programming, the int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes 
of memory for both 32 and 64-bit architectures in Java.


High-performance

Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower 
than a compiled language (e.g., C++). 

Java is an interpreted language which is why it is slower than compiled languages, e.g., C, C++, etc.


Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. 

This feature of Java makes us able to access files by calling the methods from any machine on the internet.


Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. 

The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.


Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native 
languages, i.e., C and C++.


Post updated on:  Feb 20, 2023 1:04:00 AM

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java: primitive and non-primitive.

Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float, and double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Type - In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language.

There are 8 types of primitive data types:

Boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type

Data Type Default size
boolean 1 bit
char 2 byte
byte 1 byte
short 2 byte
int         4 byte
long 8 byte
float 4 byte
double 8 byte


Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

Boolean one = false  

Byte Data Type
The byte data type is an example of a primitive data type. It is an 8-bit signed two's complement integer. Its value range lies between -128 to 127 (inclusive). Its minimum value is -128 and the maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of the "int" data type.

Example:

byte a = 10, byte b = -20  

Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and its maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like the byte data type. A short data type is 2 times smaller than an integer.

Example:

short s = 10000, short r = -5000  

Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless there is no problem with memory.

Example:
int a = 100000, int b = -200000  


Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those provided by int.

Example:
long a = 100000L, long b = -200000L  


Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is recommended to use a float (instead of a double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.

Example:
float f1 = 234.5f  


Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.

Example:
double d1 = 12.3  

Char Data Type
The char data type is a single 16-bit Unicode character. Its value range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive). The char data type is used to store characters.

Example:
char letterA = 'A'  

Post updated on:  Feb 20, 2023 1:03:19 AM


If you are a writer and struggling to monetize your work, you have found your solution. If you are a business and want to business to increase by manifolds, you are at the right place too. At ConnectClue, are your 1 solution for everything you are struggling with. You are bound to touch every height you have ever imagined if you are here with us. ConnectClue is a website that provides various services through the medium of Blog and Article Writing. They make sure that your efforts don't go to waste and that every Blog that you write, creative or Business related, reaches the right audience and helps you earn along with being known to a crowd you have only dreamt about yet. Yes, that's right. They are here to make all your dreams come true.

With this comes a question, How? and What is there for us in this?

They understand the struggle and competition of today's market and the gap that has come between the audience and the service providers. At ConnectClue, trying to bridge the same Gap through the medium of writing. Now, how you ask? It's pretty simple. Just make good quality content and start blogging with us here. They make sure that your content reaches as far as possible and they have a viewership from all around the world. Also, help us to earn through your blogs according to the viewership that you get so that our efforts are rewarded right there. Not just us, also provide free Ads, sponsorships, free business marketing, and a lot more. 

Post updated on:  Jan 28, 2023 1:29:03 PM

What is Java - Java is a high-level, robust, object-oriented, and secure programming language.

Java was developed by Sun Microsystems (which is now a subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Java Example
Let's have a quick look at the Java programming example.

Example.java

class Example{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  

To compile:
javac Example.java

To execute:
Java Example

Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

The class keyword is used to declare a class in Java.

The public keyword is an access modifier that represents visibility. It means it is visible to all.

static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. 
So, it saves memory.

void is the return type of the method. It means it doesn't return any value.

main represents the starting point of the program.

String[] args or String args[] is used for command line arguments. We will discuss it in the coming section.

System.out.println() is used to print statements. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class. 
We will discuss the internal working of system.out.println() statement in the coming section.

Java Applications

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

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

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

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

4) Mobile Application
An application that is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications.


Java Platforms: There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java. math etc. It includes core 
topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.

4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.






Post updated on:  Jan 28, 2023 1:27:44 PM

Back to top