0% found this document useful (0 votes)
2 views16 pages

Module 1.2

This document provides an overview of basic programming concepts in Java, focusing on object-oriented programming. It covers primitive data types, control flow statements, strings, and arrays, including their declaration, instantiation, and usage. Key topics include data types, control flow structures like 'if' and 'switch', and the creation and manipulation of strings and arrays.

Uploaded by

alihassan9410r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Module 1.2

This document provides an overview of basic programming concepts in Java, focusing on object-oriented programming. It covers primitive data types, control flow statements, strings, and arrays, including their declaration, instantiation, and usage. Key topics include data types, control flow structures like 'if' and 'switch', and the creation and manipulation of strings and arrays.

Uploaded by

alihassan9410r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COSC-1102

MODULE 1.2

OBJECT ORIENTED PROGRAMMING


BASIC PROGRAMMING CONCEPTS IN JAVA

PROF. DR. IMRAN SARWAR BAJWA


Department of Computer Science
The Islamia University of Bahawalpur
Basic Programming Concepts in Java

BASIC PROGRAMMING CONCEPTS IN JAVA

• Primitive Data Types


• Control Flow
• Strings
• Arrays
• Code Examples & Exercises

1. DATA TYPES
The Java programming language is statically-typed, which means that all variables must first be declared
before they can be used. This involves stating the variable's type and name, as you've already seen:

int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value
of "1". A variable's data type determines the values it may contain, plus the operations that may be
performed on it. Following are the possible data types in Java.

In Java, a primitive type is predefined by the language and is named by a reserved keyword. Primitive
values do not share state with other primitive values. The eight primitive data types supported by the Java
programming language are:
byte: The byte data type is an 8-bit (1 byte) signed two's complement integer. It has a minimum value of
-128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in
large arrays, where the memory savings matters. They can also be used in place of int where their limits
help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

COSC-1102 Object Oriented Programming 1


Basic Programming Concepts in Java

byte b = 127; or byte b = -128;

short: The short data type is a 16-bit (2 byte) signed two's complement integer. It has a minimum value
of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can
use a short to save memory in large arrays, in situations where the memory savings actually matters.

short s = 32767; or short s = -32768;

int: By default, the int data type is a 32-bit (4 byte) signed two's complement integer, which has a
minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data
type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of
232-1. Use the Integer class to use int data type as an unsigned integer.

int i = 28;

long: The long data type is a 64-bit (8 byte) two's complement integer. The signed long has a minimum
value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to
represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 64-1. Use
this data type when you need a range of values wider than those provided by int.

long l = 1234567890l; or long l = 1234567890L;

float: The float data type is a single-precision 32-bit (4 byte) IEEE 754 floating point. As with the
recommendations for byte and short, use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. This data type should never be used for precise values, such as
currency.

float f = 1.2f; or float f = 1.2F;

double: The double data type is a double-precision 64-bit (8 byte) IEEE 754 floating point. For decimal
values, this data type is generally the default choice. As mentioned above, this data type should never be
used for precise values, such as currency.

double d = 8.9;

boolean: The boolean data type has only two possible values: true and false. Use this data type for
simple flags that track true/false conditions. This data type represents one bit of information, but its "size"
isn't something that's precisely defined.

Boolean b = true;

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0)
and a maximum value of '\uffff' (or 65,535 inclusive).

COSC-1102 Object Oriented Programming 2


Basic Programming Concepts in Java

char c = ‘A’;

1.1 DEFAULT VALUES


It's not always necessary to assign a value when a field is declared. Fields that are declared but not
initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero
or null, depending on the data type. Relying on such default values, however, is generally considered bad
programming style. The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
Byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false

1.2 CHARACTER AND STRING LITERALS


Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file
system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape"
such as '\u0108' (capital C with circumflex), or "S\u00ED Se\u00F1or" (Sí Señor in Spanish).
Always use 'single quotes' for char literals and "double quotes" for String literals. Unicode escape
sequences may be used elsewhere in a program (such as in field names, for example), not just
in char or String literals.
The Java programming language also supports a few special escape sequences
for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage
return), \" (double quote), \' (single quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type. null may be assigned
to any variable, except variables of primitive types. There's little you can do with a null value beyond
testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object
is unavailable.

2. CONTROL FLOW
The control flow statements in Java allow you to run or skip blocks of code when special conditions are
met. You will use control statements a lot in your programs and this tutorial will explain how to do this.

COSC-1102 Object Oriented Programming 3


Basic Programming Concepts in Java

2.1 THE “IF” STATEMENT


The “if” statement in Java works exactly like in most programming languages. With the help of “if” you
can choose to execute a specific block of code when a predefined condition is met. The structure of the “if”
statement in Java looks like this:

If (condition){
// code here
}
The condition is Boolean. Boolean means it may be true or false. For example you may put a mathematical
equation as condition.

2.2 COMPARISON OPERATORS IN JAVA


Use this operator to create Boolean results
< less than <= less than or equal to
> greater than >= greater than or equal to
== equal to != not equal to

2.3 CONDITIONAL OPERATORS IN JAVA


The && (AND) and || (OR) operators perform Conditional-AND and Conditional-OR operations on two
Boolean expressions.

2.4 THE “IF ELSE” STATEMENT


Whit this statement you can control what to do if the condition is met and what to do otherwise. Look at
the code below”:

If (condition){
// code here
}
else{
// code here
}

2.5 THE SWITCH STATEMENT


In some cases you can avoid using multiple if-s in your code and make your code look better. For this you
can use the switch statement. Look at the following java switch example

switch (var)
{
case 3:
// code here
break;
case 4:

COSC-1102 Object Oriented Programming 4


Basic Programming Concepts in Java

// code here
break;
case 5:
// code here
break;
default:
// code here
}

The switch has a key and one or more cases. In our example the key is numOfAngles and we handle the
ceases when we give 3, 4 and 5 as values to the switch statement. If we pass a different value than 3, 4 or
5 default will be executed. Also note the break at the end of each case. If we don’t include break the
program will run to the next case. For example if we remove the break in case 3, case 3 and case 4 will be
executed in the example above.

2.6 JAVA LOOPS


There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on.
A loop statement allows us to execute a statement or group of statements multiple times and following is
the general form of a loop statement in most of the programming languages −

Java programming language provides the following types of loop to handle looping requirements. Click
the following links to check their detail.

Sr. Loop & Description


No.

1 WHILE LOOP

COSC-1102 Object Oriented Programming 5


Basic Programming Concepts in Java

Repeats a statement or group of statements while a given condition is true. It tests the condition
before executing the loop body.

while(condition)
{
// code here
}

2 FOR LOOP
Execute a sequence of statements multiple times and abbreviates the code that manages the loop
variable.

for(<initialize>; <condition>; <increment>)


{
// code here
}

3 DO...WHILE LOOP
Like a while statement, except that it tests the condition at the end of the loop body.

do
{
// code here
} while(condition);

2.7 LOOP CONTROL STATEMENTS


Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their detail.

Sr. Control Statement & Description


No.

1 break statement
Terminates the loop or switch statement and transfers execution to the statement immediately
following the loop or switch such as

break;

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating such as

COSC-1102 Object Oriented Programming 6


Basic Programming Concepts in Java

continue;

2.8 ENHANCED FOR LOOP IN JAVA


As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements
including arrays. Following is the syntax of enhanced for loop:

for(declaration : expression) {
// Statements
}

Declaration − The newly declared block variable, is of a type compatible with the elements of the array
you are accessing. The variable will be available within the for block and its value would be the same as
the current array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable
or method call that returns an array.
An example of such for loops is as below:

int[] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
[Link]( x );
[Link](",");
}

3. STRINGS
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming
language, strings are treated as objects. In addition to the eight primitive data types listed above, the Java
programming language also provides special support for character strings via
the [Link] class. Enclosing your character string within double quotes will automatically
create a new String object; for example, String s = "this is a string"; . String objects
are immutable, which means that once created, their values cannot be changed. The String class is not
technically a primitive data type.

3.1 CREATING STRINGS


The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in
this case, "Hello world!'.

COSC-1102 Object Oriented Programming 7


Basic Programming Concepts in Java

3.2 CONCATENATING STRINGS


The String class includes a method for concatenating two strings:

[Link](string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

String s = "Hello," + " world" + "!"

which results in:

"Hello, world!"

Let us look at the following example:

public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
[Link]("Dot " + string1 + "Tod");
}
}

This will produce the following result:

Dot saw I was Tod

3.3 CREATING FORMAT STRINGS


You have printf() and format() methods to print output with formatted numbers. The String class has an
equivalent class method, format(), that returns a String object rather than a PrintStream object. For
example, instead of −

[Link]("The value of the float variable is " +


"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);

COSC-1102 Object Oriented Programming 8


Basic Programming Concepts in Java

4. ARRAYS
Normally, array is a collection of similar type of elements that have contiguous memory location.
Java array is an object that contains a set of elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.

Following are a few Advantages of a Java array:


Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Following is Disadvantage of a Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in java.

4.1 TYPES OF ARRAY IN JAVA


There are two types of array.
• Single Dimensional Array
• Multidimensional Array

4.2 SINGLE DIMENSIONAL ARRAY IN JAVA


The following syntax is used to declare an array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an array in Java is also possible as below:

arrayRefVar = new datatype[size];

Example of single dimensional java array is given below, where we are going to declare, instantiate,
initialize and traverse an array.

class Testarray{
public static void main(String args[]){

COSC-1102 Object Oriented Programming 9


Basic Programming Concepts in Java

int a[]=new int[5];//declaration and instantiation


a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);

}}

Following will be the output of the above program

Output: 10
20
70
40
50

4.3 DECLARATION, INSTANTIATION AND INITIALIZATION OF JAVA ARRAY


We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5}; //declaration, instantiation and initialization

Let's see the simple example to print this array.

class Testarray1{
public static void main(String args[]){

int a[]={33,3,4,5}; //declaration, instantiation and initialization

//printing array
for(int i=0;i<[Link];i++) //length is the property of array
[Link](a[i]);

}}

Following will be the output of the above program

Output: 33
3
4
5

COSC-1102 Object Oriented Programming 10


Basic Programming Concepts in Java

4.4 PASSING ARRAY TO METHOD IN JAVA


We can pass the java array to method so that we can reuse the same logic on any array. Let's see the simple
example to get minimum number of an array using method.

class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];

[Link](min);
}

public static void main(String args[]){

int a[]={33,3,4,5};
min(a);//passing array to method

}}

Following will be the output of the above program

Output:3

4.5 MULTIDIMENSIONAL ARRAY IN JAVA


In such case, data is stored in row and column based index (also known as matrix form). Example to
instantiate Multidimensional Array in java

int[][] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

4.6 EXAMPLE OF MULTIDIMENSIONAL JAVA ARRAY


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

COSC-1102 Object Oriented Programming 11


Basic Programming Concepts in Java

class Testarray3{
public static void main(String args[]){

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}

}}

Following will be the output of the above program

Output:1 2 3
2 4 5
4 4 5

5. CODE EXAMPLES & EXERCISES


1. Write a Java program to check whether an given integer is a power of 4 or not.
Given num = 64, return true. Given num = 6, return false.

2. Write a Java program to check if a positive number is a palindrome or not.


Input a positive integer: 151
Is 151 is a palindrome number?
true

3. Write a Java program which iterates the integers from 1 to 100. For multiples of three print "Fizz"
instead of the number and print "Buzz" for the multiples of five. When number is divided by both
three and five, print "fizz buzz".

4. Write a Java program to compute the square root of an given integer.


Input a positive integer: 25
Square root of 25 is: 5

5. Write a Java program to print the ascii value of a given character.


Expected Output
The ASCII value of Z is :90

6. Write a Java program to input and display your password.


Expected Output

COSC-1102 Object Oriented Programming 12


Basic Programming Concepts in Java

Input your Password:


Your password was: abc@123

7. Write a Java program to print the following string in a specific format (see the output).
Sample Output
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are

8. Write a Java program that accepts an integer (n) and computes the value of n+nn+nnn.
Sample Output:
Input number: 5
5 + 55 + 555

9. Write a Java program to find the size of a specified file.


Sample Output:
/home/students/[Link] : 0 bytes
/home/students/[Link] : 0 bytes

10. Write a Java program to display the system time.


Sample Output:
Current Date time: Fri Jun 16 14:17:40 IST 2017

11. Write a Java program to display the current date time in specific format.
Sample Output:
Now: 2017/06/16 08:52:03.066

12. Write a Java program to print the odd numbers from 1 to 99. Prints one number per line.
Sample Output:
1
3
5
………
97
99

13. Write a Java program to accept a number and check the number is even or not. Prints 1 if the number
is even or 0 if the number is odd.
Sample Output:
Input a number: 20
1

COSC-1102 Object Oriented Programming 13


Basic Programming Concepts in Java

14. Write a Java program to convert a string to an integer in Java.


Sample Output:
Input a number(string): 25
The integer value is: 25

15. Write a Java program to calculate the sum of two integers and return true if the sum is equal to a third
integer.
Sample Output:
Input the first number : 5
Input the second number: 10
Input the third number : 15
The result is: true

16. Write a Java program to convert seconds to hour, minute and seconds.
Sample Output:
Input seconds: 86399
23:59:59

17. Write a Java program to accepts an integer and count the factors of the number.
Sample Output:
Input an integer: 25
3

18. Write a Java program to capitalize the first letter of each word in a sentence.
Sample Output:
Input a Sentence: the quick brown fox jumps over the lazy dog.
The Quick Brown Fox Jumps Over The Lazy Dog.

19. Write a Java program to convert a given string into lowercase.


Sample Output:
Input a String: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
the quick brown fox jumps over the lazy dog.

20. Write a Java program to reverse a word.


Sample Output:
Input a word: dsaf
Reverse word: fasd

21. Write a Java program to compute the sum of the first 100 prime numbers.
Sample Output:
Sum of the first 100 prime numbers: 24133

22. Write a Java program to insert a word in the middle of another string.
Insert "Tutorial" in the middle of "Python 3.0", so result will be Python Tutorial 3.0
Sample Output:
Python Tutorial 3.0

COSC-1102 Object Oriented Programming 14


Basic Programming Concepts in Java

23. Write a Java program to create a new string of 4 copies of the last 3 characters of the original string.
The length of the original string must be 3 and above.
Sample Output:
[Link].0

24. Write a Java program to extract the first half of a string of even length.
Test Data: Python
Sample Output:
Pyt

25. Write a Java program to create a string in the form short_string + long_string + short_string from two
strings. The strings must not have the same length.
Test Data: Str1 = Python
Str2 = Tutorial
Sample Output:
PythonTutorialPython

26. Write a Java program to create the concatenation of the two strings except removing the first
character of each string. The length of the strings must be 1 and above.
Test Data: Str1 = Python
Str2 = Tutorial
Sample Output:
Pythonutorial

27. Write a Java program to create a new string taking first and last characters from two given strings. If
the length of either string is 0 use "#" for missing character.
Test Data: str1 = "Python"
str2 = " "
Sample Output:
P#

28. Write a Java program to add all the digits of a given positive integer until the result has a single
digit.

COSC-1102 Object Oriented Programming 15

You might also like