Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Java.lang' - 24 code snippet(s) found

 Sample 1. Write a Program to reverse a string iteratively and recursively

Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

Strategy - Loop through each character of a String from last to first and append the character to StringBuilder / StringBuffer

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

Strategy - Call the method with substring starting from 2nd character recursively till we have just 1 character.

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

   Like      Feedback     string  StringBuffer  recursion  for loop  control statements  loop statement  stringbuffer.append  java.lang.String  java.lang.StringBuffer  String Manipulation


 Sample 2. Switch Case with Enum
Admin
info@buggybread.com
public enum State {
NEVADA, CALIFORNIA, WASHINGTON;
}

public static void method(States stateName) {
switch (stateName) {
case NEVADA:
System.out.println("You are in Nevada");
break;

case CALIFORNIA:
System.out.println("You are in California");
break;

case WASHINGTON:
System.out.println("You are in Washington");
break;
}
}

   Like      Feedback     switch case  switch  case  enum   switch with enums   switch and enums


 Sample 3. Interface Default Methods ( Base Class Definition has precedence over Interface Default Method if both are being extended and implemented and have common method definition )

HelloJava8Base 

public class HelloJava8Base {
public void defaultMethod() {
System.out.println("Default Method Base Class Implementation");
}
}

DefaultMethodInterface

public interface DefaultMethodInterface {
default public void defaultMethod() {
System.out.println("Default Method Interface Implementation");
}
}

HelloJava8

public class HelloJava8 extends HelloJava8Base implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface dmi = new HelloJava8();
dmi.defaultMethod(); // Prints "Default Method Base Class Implementation"
}
}

   Like      Feedback     interface default methods  java 8  interfaces


 Sample 4. Scheduling task using java.util.timer

static {
timer.schedule(new ScheduledTask(), 60000, 60000);
}

private static class Schedule extends TimerTask {
@Override public void run() {
//doSomething();
}
}

   Like      Feedback     java.util.timer  java.util.TimerTask  scheduling task  java.lang  Override


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Code Sample / Example / Snippet of java.lang.reflect.Field

    public Object getDeclaredField(Class targetClass, String name, Object target)

throws Exception

{

if (System.getSecurityManager() != null)

{

Actions actions = (Actions) m_actions.get();

actions.set(Actions.GET_FIELD_ACTION, targetClass, name, target);

try

{

return AccessController.doPrivileged(actions, m_acc);

}

catch (PrivilegedActionException e)

{

throw e.getException();

}

}

else

{

Field field = targetClass.getDeclaredField(name);

field.setAccessible(true);



return field.get(target);

}

}


   Like      Feedback      java.lang.reflect.Field


 Sample 6. Method to check if input String is Palindrome

private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}

   Like      Feedback     Palindrome   strBuilder.reverse   string  stringbuilder.reverse  java.lang.StringBuilder


 Sample 7. Blogger API for creating Posts ( Change xxxxxx to your blog specific info )

package Reader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;

public class BlogPostCreater {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String title, String content,String label,String authorization_key) throws IOException {

content = content.replace(""",""");


String url = "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts?clientId=xxxxxxxx&clientSecret=xxxxxxxx";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("Authorization", authorization_key);
post.setHeader("Content-type","application/json");

post.setEntity(new StringEntity(buildJson(title,content,label)));

HttpResponse response = client.execute(post);

System.out.println(response);

return "true";
}



String buildJson(String title, String content,String label) {

System.out.println(label);
return "{"status": "LIVE", "content": ""+content+"", "kind": "blogger#post"" +
", "title": ""+title+"", "url": "xxxxxx", " +
""readerComments": "DONT_ALLOW_HIDE_EXISTING", "author": {" +
""url": "https://www.blogger.com/profile/04326686331881561093", " +
""image": {" +
""url": "//lh4.googleusercontent.com/-64Ucx9lX9Q4/AAAAAAAAAAI/AAAAAAAAAx0/-rUjBgS3djE/s35-c/photo.jpg"" +
"}, " +
""displayName": "Vivek Vermani", " +
""id": "g108356395081185480077"" +
"}, "updated": "2015-09-28T09:46:12+05:30", "replies": {"totalItems": "0", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts/2495464003469367152/comments"" +
"}, "blog": {"id": "4275342475651800664"}, " +
""etag": "'GtyIIQmNmmUjEA0nwhSqMElCJ1g/dGltZXN0YW1wOiAxNDQzNDEzNzcyMDc1Cm9mZnNldDogMTk4MDAwMDAK'", " +
""published": "2015-09-28T09:46:00+05:30", " +
""id": "2495464003469367152", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxx/posts/2495464003469367152"}";
}

public String post(String url, Map<String,String> formParameters) throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);

List <NameValuePair> nvps = new ArrayList <NameValuePair>();

for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}

request.setEntity(new UrlEncodedFormEntity(nvps));

return execute(request);
}

// makes request and checks response code for 200
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);

if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}

return body;
}


}

   Like      Feedback     blogger api   blogger api for post creation  java.lang.RuntimeException


 Sample 8. Get the Maximum of two numbers

int maxNumber = Math.max(100, 500);
System.out.println(maxNumber);

   Like      Feedback     maximum of two numbers  Math.max


 Sample 9. Parse JSON using JSONParser

JSONParser jsonParser = new JSONParser();
String jsonMessage = JSONMessageAsString;

JSONObject jsonObject = null;
try {
jsonObject = (JSONObject) jsonParser.parse(jsonMessage);
} catch (ParseException e) {
System.out.println("Error in Parsing JSON");
}


Long id = (Long) jsonObject.get("Id");
String name = (String) jsonObject.get("Name");

   Like      Feedback     JSON Parsing  JSON Parser


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Clear Map entries after expiration time using Apache commons PassiveExpiringMap

PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1,TimeUnit.SECONDS); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1")); // prints true
Thread.sleep(1000);
System.out.println(cache.containsKey("Key1")); // prints false

   Like      Feedback     Clear Map entries after expiration  PassiveExpiringMap  map  apache commons  TimeUnit.SECONDS  Thread.sleep


 Sample 11. Make a map readonly using Apache Commons UnmodifiableMap

Map<String,String> map = new HashMap();
map.put("Key1", "Value1");

Map<String,String> unmodifiableMap = UnmodifiableMap.unmodifiableMap(map);
      
unmodifiableMap.put("Key2", "Value2"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     readonly map  apache commons


 Sample 12. Make a Map entry read only using Apache Commons UnmodifiableMapEntry

Entry entry = new UnmodifiableMapEntry("Key2", "Value2");
entry.setValue("Value3"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     read only map entry  UnmodifiableMapEntry  Apache commons collections


 Sample 13. Get the properties of class (i.e package name , interfaces , subclasses etc ) using ClassUtils( Apache Commons )

Class class1 = ClassUtils.getClass("BuggyBreadTest"); 
System.out.println(ClassUtils.getPackageName(class1));
System.out.println(ClassUtils.getAllInterfaces(class1));

   Like      Feedback     ClassUtils  Apache Commons  Get Class Properties  java.lang.Class


 Sample 14. Create an UnmodifiableMultiSet ( Read only set allowing multiple values ) using Apache Commons

MultiSet<String> multiSet = new HashMultiSet(); 
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");

System.out.println(multiSet); // Prints [Albama:3]
      
UnmodifiableMultiSet<String> unmodifiablemultiSet = (UnmodifiableMultiSet<String>) MultiSetUtils.unmodifiableMultiSet(multiSet);

unmodifiablemultiSet.add("Albama"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     UnmodifiableMultiSet  Apache Commons Collections  Set  MultiSet


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Usage of java.lang.reflect.Field;

Form form1 = resources.getForm("fr", "", "", "testForm1_fr");
Field field1 = form1.getField("testProperty1");

   Like      Feedback     Reflection   java.lang.reflect.Field


 Sample 16. Usage of java.lang.reflect.Modifier

Field f = DomainValidator.class.getDeclaredField(arrayName);
final boolean isPrivate = Modifier.isPrivate(f.getModifiers());
if (isPrivate) {
f.setAccessible(true);
}

   Like      Feedback     Reflection  java.lang.reflect.Modifier


 Sample 17. Usage of org.apache.commons.validator.ValidatorAction

ValidatorAction va = new ValidatorAction();
va.setName(action);
va.setClassname("org.apache.commons.validator.ValidatorTest");
va.setMethod("formatDate");
va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");

FormSet fs = new FormSet();
Form form = new Form();
form.setName("testForm");
Field field = new Field();
field.setProperty(property);
field.setDepends(action);
form.addField(field);
fs.addForm(form);

resources.addValidatorAction(va);
resources.addFormSet(fs);

   Like      Feedback     Apache Commons  ValidatorAction  FormSet


 Sample 18. Usage of java.lang.reflect.ParameterizedType

ParameterizedType ptype = (ParameterizedType)type;
Class raw = (Class)ptype.getRawType();

   Like      Feedback     Reflection  ParameterizedType


 Sample 19. Code Sample / Example / Snippet of java.lang.reflect.Type

  public static Type stripGenerics(Type type) {

if (type instanceof GenericArrayType) {

final Type componentType =

((GenericArrayType) type).getGenericComponentType();

return new ArrayType(stripGenerics(componentType));

} else if (type instanceof ParameterizedType) {

return ((ParameterizedType) type).getRawType();

} else {

return type;

}

}


   Like      Feedback      java.lang.reflect.Type


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Mark a method as deprecated

@Deprecated
public Employee getEmployee(int employeeId){

}

   Like      Feedback     deprecate   deprecated annotation


 Sample 21. Code Sample / Example / Snippet of java.lang.reflect.Method

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

try {

Method bridge = handler.getClass().getMethod(method.getName(), method.getParameterTypes());

bridge.setAccessible(true);

return bridge.invoke(handler, args);

}

catch (NoSuchMethodException ex) {

return super.invoke(proxy, method, args);

}

catch (InvocationTargetException ex) {

throw ex.getCause();

}

}


   Like      Feedback      java.lang.reflect.Method


 Sample 22. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassElementValueGen

    public void testCreateClassElementValue() throws Exception

{

final ClassGen cg = createClassGen("HelloWorld");

final ConstantPoolGen cp = cg.getConstantPool();

final ObjectType classType = new ObjectType("java.lang.Integer");

final ClassElementValueGen evg = new ClassElementValueGen(classType, cp);

assertTrue("Unexpected value for contained class: '"

+ evg.getClassString() + "'", evg.getClassString().contains("Integer"));

checkSerialize(evg, cp);

}


   Like      Feedback      org.apache.bcel.generic.ClassElementValueGen


 Sample 23. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantCP

    public String getClassName( final ConstantPoolGen cpg ) {

final ConstantPool cp = cpg.getConstantPool();

final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());

final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);

if (className.startsWith("[")) {

return "java.lang.Object";

}

return className.replace('/', '.');

}


   Like      Feedback      org.apache.bcel.classfile.ConstantCP


 Sample 24. Usage of java.lang.module.ModuleReference , java.lang.module.ModuleDescriptor and java.lang.module.ResolvedModule;

 for (ResolvedModule resolvedModule : cf.modules()) {
ModuleReference mref = resolvedModule.reference();
ModuleDescriptor descriptor = mref.descriptor();
String name = descriptor.name();
URI uri = mref.location().orElse(null);
ClassLoader loader = moduleToLoader.get(resolvedModule.name());
Module m;
if (loader == null && name.equals("java.base")) {
// java.base is already defined to the VM
m = Object.class.getModule();
} else {
m = new Module(layer, loader, descriptor, uri);
}
nameToModule.put(name, m);
moduleToLoader.put(name, loader);
}

   Like      Feedback     



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner