Sunday, October 21, 2018

Changing Case of Character in BlueJ



import java.io.*;
class CaseChanging

{
 BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
char ch;

public void take() throws Exception
{
 System.out.print("\nEnter the character:");
ch=(char)br.read();
System.out.println("Entered Character is:”+ch);
ch=Character.toUpperCase(ch);
System.out.println("Modified Character is:”+ch);
}


public static void main(String args[]) throws Exception
{
 CaseChanging ob=new CaseChanging ();
ob.take();
}
}





import java.io.*;
class CaseChanging

{
 BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
char ch;

public void take() throws Exception
{
 System.out.print("\nEnter the character:");
ch=(char)br.read();
System.out.println("Entered Character is:”+ch);
ch=Character.toLowerCase(ch);
System.out.println("Modified Character is:”+ch);
}

public static void main(String args[]) throws Exception
{
 CaseChanging ob=new CaseChanging ();
ob.take();
}
}

Monday, October 15, 2018

BlueJ Program on Letter Checking in a sentence



import java.io.*;
class LetterCh
{
  BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
int I,len,c=0;
char ch;
public void showLetters () throws Exception
{
 System.out.print("\nEnter the sentence:");
String str=br.readLine();
str=str.trim();
len=str.length ();
for (i=0;i< len;i++)

{
ch= str.charAt(i);
if(Character.isLetter(ch))
c++;
}
System.out.print(“Total number of Letters in the sentence=”+c);
}

public static void main(String args[])
{
LetterCh ob=new LetterCh ();
ob. showLetters();
}
}

Thursday, October 11, 2018

BlueJ Program on Digit Checking in a sentence



class DigitCh
{

int I,len,c=0;
char ch;
public void showDigits (String str)
{
str=str.trim();
len=str.length ();
for (i=0;i< len;i++)

{
ch= str.charAt(i);
if(Character.isDigit(ch))
c++;
}
System.out.print(“Total number of digits in the sentence=”+c);
}

public static void main(String args[])
{
DigitCh ob=new DigitCh ();
ob. showDigits(“abcd123”);
}
}


Wednesday, October 10, 2018

BlueJ Program on Letter or Digit Checking in a sentence



import java.io.*;
class LetterCh
{
  BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
int I,len,c=0;
char ch;
public void showLettersDigits () throws Exception
{
 System.out.print("\nEnter the sentence:");
String str=br.readLine();
str=str.trim();
len=str.length ();
for (i=0;i< len;i++)

{
ch= str.charAt(i);
if(Character.isLetterOrDigit(ch))
c++;
}
System.out.print(“Total number of Letters and Digits in the sentence=”+c);
}

public static void main(String args[])
{
LetterCh ob=new LetterCh ();
ob. showLettersDigits();
}
}


Monday, October 8, 2018

Character Class in Java



Character is a class of java.lang package. Character  is a simple wrapper class and constructor of this class is Character (char ch), where the char ch is wrapped by the Character  object. Character class has several static methods which are used for several purposes


Return Type
Prototype
Use
boolean
static boolean isDigit (char ch)
Returns true if the argument character is digit otherwise false
boolean
static boolean isLetter (char ch)
Returns true if the argument character is an alphabet  otherwise false
boolean
static boolean isLetterOrDigit (char ch)
Returns true if the argument character is digit or alphabet otherwise false
boolean
static boolean isLowerCase (char ch)
Returns true if the argument character is a lowercase letter otherwise false
boolean
static boolean isUpperCase (char ch)
Returns true if the argument character is a uppercase letter otherwise false
boolean
static boolean isWhitespace (char ch)
Returns true if the argument character is a white space otherwise false
char
static char toLowerCase (char ch)
Returns lower case equivalent of the argument  character if it is in upper case otherwise returns the same value
char
static char toUpperCase (char ch)
Returns upper case equivalent of the argument  character if it is in lower case otherwise returns the same value

Saturday, September 29, 2018

Scope and Life Time of a Variable



Whenever we declare any variable, it is declared within a block (enclosed by curly braces). That particular block is known as scope or life time of a variable.

Let’s describe it with example:

class Sc
{
public void take (int a, int b)
{
int x=a+b;
}

public void show ()
{
System.out.print(x);
}
public static void main(String args[])
{
 Sc ob=new SC();
ob.take(2,3);
ob.show();
}
}

The above program will show compile time error as variable ‘x’ is not accessible within function public void show () as the variable is declared within the function public void take (). Scope and life time of the variable is confined within that function. The correct program would be as follows:

class Sc
{
int x;
public void take (int a, int b)
{
 x=a+b;
}

public void show ()
{
System.out.print(x);
}
public static void main(String args[])
{
 Sc ob=new SC();
ob.take(2,3);
ob.show();
}
}


Loop, if body etc also defines block so variables declared within that block will not be accessible outside.

Type Casting or Type Conversion in BlueJ


Casting or type conversion means converting one type of value into other type. There are two types of casting :
1.    Implicit  / Automation casting
2.    Explicit / Forceful casting

Implicit Casting: When variable or variables are automatically converted into other type during execution of any expression, it is known as implicit casting or conversion.

In java, also in other languages, expression execution among different type of variables is not possible. All the variables must be of same type before execution of the expression. What will happen if we use integer type,long type and double type variables in any expression? The value of integer type and long type variables will be automatically converted into double type value before the execution of the expression and this is known as implicit or automatic casting. In implicit casting, values in variables with lower hierarchical order are automatically converted into values of variable type with higher hierarchical order. 

Examples of Implicit Casting

int num1=10;
long num2=100000;
double num3=num1 + num2;

Value of num3 would be 100010.00

Another example:

int a=10;
double b=10.5;
double c=a+b;

Value of c would be 10.50


Explicit Casting

In many cases, two or more same type of variables are used in any expression but the result should be in another type. How to get it? Suppose we want to display the average marks obtained by a student. Here is a program to demonstrate explicit casting.

class Avg
{
public void show (int marks, int no)
{
double av=marks/no;
System.out.print(“Average marks=”+av);
}
}

If total marks obtained by the student is 250 and number of subjects is 3, output of the program will be 83.00

Why so? Integer division gives quotient only. When 250 is divided by 3, it gives 83, not 83.33. 83 is stored in double variable so it is implicitly casted into double. To get the exact result, one of the variables in the expression is to be explicitly casted into double, so that double value divided by int will be ultimately double divided by double (implicit casting) and the result will be in double. So the program would be:

class Avg
{
public void show (int marks, int no)
{
double av=(double) marks/no;
System.out.print(“Average marks=”+av);
}
}

So, explicit casting is the technique where one of the variables in any expression is converted into any specific type so that others will implicitly casted into that type. Syntax of explicit casting is to write the target type within bracket before anyone of the variables in the expression.

What are the advantages and disadvantages of casting or conversion

Advantage: We can get our results as desired through type casting.
                   We can convert one type of variable or object to other type

Disadvantage: Chances of loss in precision

e.g:
int a;
double b=100.25;
a=(int) b;
Now the value of ‘a’ is 100. 0.25 is lost

Wednesday, August 29, 2018

More String Methods in Python Programming Language


Mrthods and Description
 String capitalize()

Converts first character to Capital Letter

Return type of this method is String and the method is invoked using a string object and takes no argument or parameter.
str1="i am Indian"
str2=str1.capitalize()
str2 would be 'I am Indian' where str1 will remain the same ('i am Indian')

For non alphabetic letter at the first position of the string, there will be no change.
str1="# i am Indian"
str2=str1.capitalize()

str2 would be '# i am Indian' 
String center()

Pads string with specified character

Return type of this method is String and the method is invoked using a string object and takes int value and character (optional) as arguments or parameters. 
This method returns the invoking string centered in width specified in first argument. Padding is done using the specified character passed as second argument, if any character is passed. Default filler character is a space.

str = "Mera Bharat Mahan"

print str.center(21, '#')
The output would be  : "##Mera Bharat Mahan##"

Again the statement print str.center(21) would produce the output "  Mera Bharat Mahan  "
String casefold()

converts to casefolded strings

Return type of this method is string and the method is invoked using a string object. The casefold() method returns a string where all the characters are lower case.


This method is similar to the lower() method, but the casefold() method is stronger, more aggressive, meaning that it will convert more characters into lower case.
String count()

returns occurrences of substring in string

Return type of this method is int, the method is invoked using a string object and takes argument (s) or parameters. Syntax of this method is string.count(substring, int start, int end): The second and third arguments are optional. 'string' is the invoking string from where the substring will be searched. 'substring' is the string which will be searched in 'string'. 'start' indicates the index from where search will be performed and 'end' is the end index of searching. If the second and third arguments are not passed, the searching will be performed on the entire string.
boolean endswith()

Checks if String Ends with the Specified Suffix

Return type of this method is boolean, the method is invoked using a string object and takes argument (s) or parameters. Syntax of this method is boolean endswith(substring, int start, int end): The second and third arguments are optional. 'string' is the invoking string from where the substring will be searched. 'substring' is the string which will be searched in 'string'. 'start' indicates the index from where search will be performed and 'end' is the end index of searching. If the second and third arguments are not passed, the searching will be performed on the entire string. If the search is successful, the method returns true otherwise false.

str = "this is testing";

suffix = "testing";
print str.endswith(suffix)
print str.endswith(suffix,20)

suffix = "is";
print str.endswith(suffix, 2, 4)
print str.endswith(suffix, 2, 6)

Output

True
True
True

False
String expandtabs()

Replaces Tab character With Spaces

The expandtabs() method returns a copy of string with all tab characters '\t' replaced with whitespace characters.

Return type of this method is string, the method is invoked using a string object and may or may not take parameter while invoking the method. If the method is invoked without parameter then each '\t' will be replaced by 8 whitespace characters otherwise the number of whitespace characters will be same as the integer value passed as argument.

str = 'abc\txyz'
result = str.expandtabs()
print(result)

Output
abc        xyz
String encode()

returns encoded string of given string
String find()

Returns the Lowest Index of Substring

Return type of this method is integer, the method is invoked using a string object and takes a string, start index and end index as parameters. Second and third arguments are optional. 

The method searches the argument string in the invoking string and if found, it returns the first occurrence index otherwise returns -1. If the 2nd and 3rd arguments are passed, it will search the  argument string within the specified indexes.


str1 = 'Mata o mata'
result = str1.find('mata')
print("Substring 'mata':", result)
result = str1.find('pita')
print("Substring 'pita ':", result)

Output

7
-1
String format()

formats string into nicer output
 String index()

String isalnum()

Checks Alphanumeric Character


Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If the invoking string contains alphanumeric characters only it returns true otherwise false.

str1 = "So234MA"
print(str1.isalnum())


str1 =  "So 234MA"
print(str1.isalnum())

str1 =  "HiSoma"
print(str1.isalnum())

str1 = "3156"
print(str1.isalnum())

Output

True
False
True
True
 String isalpha()

Checks if All Characters are Alphabets

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If the invoking string contains alphanumeric characters only it returns true otherwise false.

str1 = "So234MA"
print(str1.isalpha())


str1 =  "Soma Das"
print(str1.isalpha())

str1 =  "HiSoma"
print(str1.isalpha())

str1 = "3156"
print(str1.isalpha())

Output

False
False

True
False
 String isdecimal()

Checks Decimal Characters

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If the invoking string contains decimal only it returns true otherwise false.

str1 = "So234MA"
print(str1.isdecimal())


str1 =  "Soma Das"
print(str1.isdecimal())

str1 =  "HiSoma"
print(str1.isdecimal())

str1 = "3156"
print(str1.isdecimal())

Output

False
False

False
True

String isdigit()

Checks Digit Characters

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If the invoking string contains digits only it returns true otherwise false.

str1 = "So234MA"
print(str1.isdigit())


str1 =  "Soma Das"
print(str1.isdigit())

str1 =  "HiSoma"
print(str1.isdigit())

str1 = "3156"
print(str1.isdigit())

Output

False
False

False

True
String isidentifier()

Checks for Valid Identifier
String islower()

Checks if all Alphabets in a String are Lowercase

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If all the alphabets in the invoking string are in lower case only it returns true otherwise false. The string may contain digits, whitespaces.

str1 = "So234MA"
print(str1.islower())


str1 =  "Soma Das"
print(str1.islower())

str1 =  "hi soma"
print(str1.islower())


Output

False
False

True


String isnumeric()

Checks Numeric Characters

A numeric character may be Decimal, Digit or Numeric

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If all the alphabets in the invoking string are numeric characters, the method would return true otherwise false.
String isprintable()

Checks Printable Character

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If all the characters in the invoking string are pritable characters, the method would return true otherwise false.

Characters that occupies printing space on the screen are known as printable characters like letters and symbols, digits, punctuation and whitespace

s = 'We can print space'
print(s)
print(s.isprintable())

s = '\nNew Line Character is printable'
print(s)
print(s.isprintable())

s = '' "

print('\nEmpty string also printable', s.isprintable())
String isspace()


Checks Whitespace Characters

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument. If all the characters in the invoking string are space, the method would return true otherwise false.

s1 = '   \t'
print(s1.isspace())

s1 = ' abcd '
print(s1.isspace())

Output

True
False
String istitle()


Checks for Titlecased String

Return type of this method is boolean (true or false). T
he method is invoked using a string object and takes no argument.

The method returns true if an uppercase character is followed by a lowercase character or uncased character and if an uppercase character proceeds a character that character must be an uncased character.

The method returns false if no uppercase characters, if uppercase follows a lowercase character with no whitespace between the characters, if uppercase follows another uppercase with no whitespace.


Whitespace is a non case character.

str1 = "Master Code Online"
 str1.istitle()
True

str1 = "master code online"
 str1.istitle()

False
String isupper()

returns if all characters are uppercase characters

Return type of this method is boolean (true or false). The method is invoked using a string object and takes no argument.

The method returns true if all the characters in the invoking string are in uppercase.

The method returns false if all the characters in the invoking string are in lowercase.



str1 = "Master Code Online"
 str1.isupper()
False

str1 = "SOMA DAS"
 str1.isupper()


True
String join()

Returns a Concatenated String


Return type of this method is string. The method is invoked using a string object and takes a string, list or tuple as argument.

The join() method provides a flexible way to concatenate string. It concatenates each element of an iterable (such as list, string and tuple) to the string and returns the concatenated string.

The syntax of join() is: string.join(iterable)

list = ['1', '2', '3', '4']
sp = ', '
print(sp.join(list))

Output: 1, 2, 3, 4

tup = ('1', '2', '3', '4')
print(sp.join(numTuple))

Output: 1, 2, 3, 4

s1 = 'abc'
s2 = '123'

""" Each character of s2 is concatenated to the front of s1""" 
print('s1.join(s2):', s1.join(s2))


Output: s1.join(s2): 1abc2abc3


""" Each character of s1 is concatenated to the front of s2""" 

print('s2.join(s1):', s2.join(s1))

Output: s2.join(s1): a123b123c
String ljust()

returns left-justified string of given width

Return type of this method is string. The method is invoked using a string object and takes no argument.

The syntax of ljust() method is: string.ljust(width[, fillchar])
Here, fillchar is an optional parameter.

The ljust() method creates 'width' number of character spaces sets the string within that space in left-justified order.

If the second argument 'fillchar' is passed, it also fills the remaining space with the defined character.

Example:

str1 = 'India'
width = 7
fillchar='#'
# print left justified : print(str1.ljust(width))

Output

I
n
d
i
a
 #


str1 = 'India'
width = 7
# print left justified : print(str1.ljust(width))

Output

I
n
d
i
a


returns right-justified string of given width

returns right-justified string of given width

Return type of this method is string. The method is invoked using a string object and takes no argument.

The syntax of rjust() method is: string.rjust(width[, fillchar])
Here, fillchar is an optional parameter.

The rjust() method creates 'width' number of character spaces sets the string within that space in right-justified order.

If the second argument 'fillchar' is passed, it also fills the remaining space with the defined character.

Example:

str1 = 'India'
width = 7
fillchar='@ '
# print right justified : print(str1.rjust(width))

Output

@
@
I
n
d
i
a


str1 = 'India'
width = 7
# print right justified : print(str1.rjust(width))

Output



I
n
d
i
a
String lower()

returns lowercased string
String upper()

returns uppercased string
String swapcase()

swap uppercase characters to lowercase; vice versa
String lstrip()

Removes Leading Characters
String rstrip()

Removes Trailing Characters
String strip()

Removes Both Leading and Trailing Characters
String partition()

Returns a Tuple
String maketrans()

returns a translation table
String rpartition()

Returns a Tuple
String translate()

returns mapped charactered string
String replace()

Replaces Substring Inside
String rfind()

Returns the Highest Index of Substring
String rindex()

Returns Highest Index of Substring
String split()

Splits String from Left
String rsplit()

Splits String From Right
String splitlines()

Splits String at Line Boundaries
String startswith()

Checks if String Starts with the Specified String
String title()

Returns a Title Cased String
String zfill()

Returns a Copy of The String Padded With Zeros
String format_map()

Formats the String Using Dictionary
any()

Checks if any Element of an Iterable is True
all()

returns true when all elements in iterable is true
ascii()

Returns String Containing Printable Representation
bool()

Coverts a Value to Boolean
bytearray()

returns array of given byte size
bytes()

returns immutable bytes object
compile()

Returns a  code object
complex()

Creates a Complex Number
enumerate()

Returns an Enumerate Object
filter()

constructs iterator from elements which are true
float()

returns floating point number from number, string
input()

reads and returns a line of string
int()

returns integer from a number or string
iter()

returns iterator for an object
 len()

Returns Length of an Object
max()

returns largest element
min()

returns smallest element
map()

Applies Function and Returns a List
 ord()

returns Unicode code point for Unicode character
reversed()

returns reversed iterator of a sequence
slice()

creates a slice object specified by range()
sorted()

returns sorted list from a given iterable
sum()

Add items of an Iterable
zip()

Returns an Iterator of Tuples

Google+ Followers

Subscribe via email

Enter your email address:

Delivered by FeedBurner