Saturday 5 January 2019

Methods In Java




Today we are going to learn the method (s) in java. We can not write all the logic inside main() method.

We need to separate block of code to perform specific takes.



Ques -- What is a method (s) in java?

Answer -- Method is a set of statements (instruction/code) to perform a specific task/operation.


Ques -- Why we create methods?

Answer -- because of Reusability of code.


Ques -- How we can create a method (s)?

Answer --

Access Modifires -- public, private, protected, no access specifire (default)
Specifires -- static,stictfp,volatile,syncornized etc
Return Type -- void, int, boolean etc

[ Will discuss these keywords in our next post ]


Ques -- How can we call a method (s) in java?

Answer --  There are two types of methods in java

  1. static method
  2. instance method

1 ) Static Methods



1 ) Instance Methods





# One Example of Add and Subtract method in java 





package com.method.blog.demo;

//going to create 2 methods
// 1 - static method 
// 2 - instance method (non-static method)


public class MethodDemo {

//method 1 -- static method
// return type is void
// taking two arguments

public static void addMethod(int num1,int num2){
int sum = num1 + num2;
System.out.println("sum is "+ sum);
}

//method 2 -- non-static method
//return type -- int
// taking two argument

public int subtractMethod(int num1,int num2){
int sub = num1 - num2;
return sub; // return type is must
}

public static void main(String[] args) {
// creating objectof the class
MethodDemo md = new MethodDemo();

// static method call
// this method wont return any thing
MethodDemo.addMethod(5, 6);

// non- static method call
//this method return -- integer value
int result = md.subtractMethod(6,5);
System.out.println("Subtaction is "+result);
}
}




Practice Programming Questions In Java ( Part 3 )




Today I am going to give you more programming questions based on String.
These programs are very important and useful for  Interview and Viva.

Try to solve these Questions in both ways -- using with/without string pre-defined methods.


Question 1 - WAP to read a string from the user and print it in double quotes?

input -- I am Java From Basics
output -- " I am Java From Basics "
Hint -- escape characters


Question 2 - WAP to reverse String in Java using Iteration and Recursion?


Question 3 - How to check if a String contains only digits?


Question 4 - How to find duplicate characters in a String?
Input - "Programming"
output -
g : 2
r : 2
m : 2


*Question 5 - How to count the occurrence of a given character in String?

[Hint -- This can be easily done using Map(Collection in java kind of Data Structure) and it is very important Ques for Interview]


Question 6 - How to check if String is Palindrome?


Question 7 - Also Check palindrome for the number?


Question 8 - WAP to reverse words in a sentence with/without using the method?

  1. Input -- I am a boy.      Output -- boy a am I
  2. Input -- I am a boy.      Output -- yob a ma I




This is one more site -- to solve more question on strings -- " javarevisited.blogspot.com "




Friday 19 October 2018

String, String Buffer & String Builder (Part 3)




Hey Guyz,

There are some difference between String, String Buffer and String Builder. We discuss String and its methods. We have some more methods in String buffer and Builder to modify strings. 


String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.








String, String Buffer and String Builder



String and String Buffer



String Buffer and String builder is almost the same (excepts 2-3 differences).

You can refer this site -- gives the proper difference between these terms. 
String vs StringBuffer vs StringBuilder  ---  www.journaldev.com 




Strings In Java (Part 1)




Hey guys,

Today we are going to start a new topic and this topic is very important for interview purpose as well as for job/doing coding.


" String is a CLASS in Java.."  String is a sequence of characters.

There are two ways to get string object in java

  1. using new keyword
  2. using literal constant


1 ) Using a new keyword. 

whenever we want to create an object, we must know about the constructor of it.
String class has 2 Constructors.
  1. no argument constructor [ String() ]
  2. one argument constructor [ String(String s) ]
Note - Both are same no difference, just a way of writing (Syntax) is different because of the constructor. 




2) literal Way



Question  -- what is the diffrence between String s = new String("Hello"); and String s = "Hello";  ?

Answer -

String s1="hello";

The string literal "hello" will be created and this would be placed in the String constant pool. (constant pool is a special memory for String literal. )

Hence one object is created with s1 as a reference variable to it.

Also, when any other reference variable is created in future with the same value as "hello", it would refer to the already created String literal present in the constant pool rather than creating a new one.


String s1=new String("hello");

In this case, two objects would be created.One would be the same string literal as above and would be placed in String constant pool. The second object would be created and placed in the normal(non pool) memory and s1 would refer to it. The second object would act as a normal object in a heap.



In short,

String S1 = new String("Hello");
This statement creates a String object in the Heap Memory.

String S1 = "Hello";
This statement creates a String literal with value "Hello" in the String Pool.

For more understanding, let's take 3 cases.

Case 1. String Object and Literal

String s1 = "Hello";
String s2 = new String("Hello");

Since s1 and s2 are reference variables, they'd be pointing at their respective memory locations right ?

s1 points to String Pool's location
and
s2 points to Heap Memory location.

Now testing if they're equal:
if(s1 == s2) 
would return false, as the reference variables are checked.

Whereas
s2.equals(s1) 
will return true as equals function checks the individual characters in both the reference variables.


An Interesting Fact:
"String Literal Pool" is a memory area that contains all the string literals used in the program.
Whenever a new literal is encountered, the JRE checks if it exists in the String pool or not. It does not contain duplicate literals.

If you create two reference variables with the same value "Hello", they'd both point to the same location.

Case 2: Two String Literals:

Eg:
String s1 = "Hello";
String s2 ="Hello";

if(s1==s2) 
will be true.

Case 3: One string object and anonymous literal

String s1 = new String("Hello");

if(s1 == "Hello")
will be false.

In this case, "Hello" creates a literal in the pool which has a different memory location than S1's heap memory.


Source  -- quora 






Strings in Java (Part 2)




Hey Friendz.

In this post, we are going to discuss string-specific methods. these methods are very useful, at the time of programming.

There are more than 40 methods in Java 1.7. Here, we are going to discuss the most common methods.



char charAt(int index)

Returns the character at the specified index.

String concat(String str)

Concatenates the specified string to the end of this string.

boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

int length()

Returns the length of this string.

boolean matches(String regex)

Tells whether or not this string matches the given regular expression.

String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

String[] split(String regex)

Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.

char[] toCharArray()

Converts this string to a new character array.

String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

String substring(int beginIndex)

Returns a new string that is a substring of this string.

String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the default locale

String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the default locale.

String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.


♣♣  Compaire two Strings

  1. Based On Memory Location [ == ]
  2. Based On String sequence [ .equals() ]
  3. Based On Lexicographical order [ compaireTo ]

refer this website  -- www.baeldung.com






Here are the links and videos... You can find good programs here and please understand all logical concept from here and practice all logical programs...to become a good java developer.

beginnersbook -- Go Here

Java CodeExample -- Go Here (one more good site) 




# Videos 




String Part 1




String Part 2